基本上,我試圖讓我為物件創建的類能夠讀出單個專案,以便我可以使用它們。我在使用 foreach 回圈時遇到問題
這是我想閱讀的 Json 的副本
// "roles": [
// {
// "name": "All Modules",
// "oid": "G|2",
// "uuid": "06be0407-53f9-4a0a-9b97-e771631e8d83",
// "study": true,
// "site": false,
// "href": "coming soon"
// }
這是我使用的課程
namespace SomeNamespace
{
public class Roles
{
[JsonProperty("name")]
public string name { get; set; }
}
public class RolesJson
{
[JsonProperty("roles")]
public Roles roles { get; set; }
}
}
這是我的 RequestExample.cs
var outputString = $"{await response.Content.ReadAsStringAsync()}";
//Console.WriteLine(outputString);
JObject stuff = JObject.Parse(outputString);
Console.WriteLine(stuff);
//The Response body is the following:
//{
// "roles": [
// {
// "name": "All Modules",
// "oid": "G|2",
// "uuid": "06be0407-53f9-4a0a-9b97-e771631e8d83",
// "study": true,
// "site": false,
// "href": "coming soon"
// }
// ]
//}
foreach (JObject jo in stuff["roles"])
{
foreach (var item in jo)
{
Console.WriteLine(item);
}
// Console.WriteLine(jo.ToString());
//prints this
//{
// "name": "All Modules",
// "oid": "G|2",
// "uuid": "06be0407-53f9-4a0a-9b97-e771631e8d83",
// "study": true,
// "site": false,
// "href": "coming soon"
//}
}
uj5u.com熱心網友回復:
你可以使用這個網站https://app.quicktype.io/來創建類
public partial class Data
{
[JsonProperty("roles")]
public List<Role> Roles { get; set; }
}
public partial class Role
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("oid")]
public string Oid { get; set; }
[JsonProperty("uuid")]
public Guid Uuid { get; set; }
[JsonProperty("study")]
public bool Study { get; set; }
[JsonProperty("site")]
public bool Site { get; set; }
[JsonProperty("href")]
public string Href { get; set; }
}
并反序列化您的資料
List<Role> roles=JsonConvert.DeserializeObject<Data>(json).Roles;
Role role = roles[0];
string name = role.Name;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/510647.html
標籤:C#数组json林克目的
