[英]C# JObject Unexpected token when deserializing multidimensional array
I am using JObject to read various api responses.我正在使用 JObject 来读取各种 api 响应。 With the following json使用以下 json
{"API":{"Year":["2020","2019","2018","2017","2016","2015"],
"Status": {"Message":"The call returned successfully with years"}}}
I can use this:我可以用这个:
dynamic json= JObject.Parse(s);
string[] yrs = json.API.Year.ToObject<string[]>();
where s is the json object.其中 s 是 json 对象。 This works perfectly to give me a simple array of years.这非常适合给我一个简单的年份数组。 I am having difficulty parsing multi dimensions in the json response.我在解析 json 响应中的多维时遇到困难。 when i have the following:当我有以下内容时:
{"API":{"Category":[
{"GroupName":"Exterior Accessories","GroupID":"2",
"Items":
[{"Id":"64","Value":"Body Part"},
{"Id":"20","Value":"Body Styling"},
{"Id":"7","Value":"Bras and Hood Protectors"}]
},
{"GroupName":"Interior Accessories","GroupID":"4",
"Items":
[{"Id":"21","Value":"Carpet",
{"Id":"2","Value":"Doors and Components"},
{"Id":"8","Value":"Floor Protection"}]
},
],
"Status": {"Message":"The call (api.v12.estore.catalograck.com) returned successfully with categories.","DataFound":true,"TimeStamp":"02/02/2020 11:48:27","InternalError":false}}}
How can I parse this into a multi-dimensional array?如何将其解析为多维数组?
Since Years you used was a simple built in element (string), you dont need to create any classes.. but the Categories you have in your JSON is a object.由于您使用的 Years 是一个简单的内置元素(字符串),因此您不需要创建任何类..但是您在 JSON 中的类别是一个对象。 To access the Categories in a way you can access its elements, I would recommend creating the necessary classes and then using the Category list of the root object to do what you need.要以一种可以访问其元素的方式访问类别,我建议创建必要的类,然后使用根对象的类别列表来执行您需要的操作。
Example code示例代码
public class Item
{
public string Id { get; set; }
public string Value { get; set; }
}
public class Category
{
public string GroupName { get; set; }
public string GroupID { get; set; }
public List<Item> Items { get; set; }
}
public class Status
{
public string Message { get; set; }
public bool DataFound { get; set; }
public string TimeStamp { get; set; }
public bool InternalError { get; set; }
}
public class API
{
public List<Category> Category { get; set; }
public Status Status { get; set; }
}
public class RootObject
{
public API API { get; set; }
}
Above are the needed classes for succesful deserialization where RootObject class is the parent.以上是成功反序列化所需的类,其中 RootObject 类是父类。
Use the following in your Main method.,在您的 Main 方法中使用以下内容。,
RootObject root = JsonConvert.DeserializeObject<RootObject>(json);
List<Category> categories = root.API.Category;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.