我解析了这个Json:
{
"text": "Sample Text",
"id": 123456789,
"user": {
"name": "ExampleUser",
"id": 123,
"screen_name": "ExampleUser"
},
"in_reply_to_screen_name": null,
}
到我的c#类RootObject:
public class User
{
public string name { get; set; }
public int id { get; set; }
public string screen_name { get; set; }
}
public class RootObject
{
public string text { get; set; }
public long id { get; set; }
public User user { get; set; }
public object in_reply_to_screen_name { get; set; }
}
像这样:
RootObject h = JsonConvert.DeserializeObject<RootObject>(string);
所有这一切都很完美,但现在我想解析所有先前json对象的数组。
例如这个Json数组:
[
{
"text": "Sample Text",
"id": 123456789,
"user": {
"name": "ExampleUser",
"id": 123,
"screen_name": "ExampleUser"
},
"in_reply_to_screen_name": null,
},
{
"text": "Another Sample Text",
"id": 101112131415,
"user": {
"name": "ExampleUser2",
"id": 124,
"screen_name": "ExampleUser2"
},
"in_reply_to_screen_name": null,
}
]
我创建了另一个类:
public class ListRoot {
public List<RootObject> status { get; set; }
}
然后使用相同的方法:
ListRoot h = JsonConvert.DeserializeObject<ListRootObject>(string);
但它不起作用。你知道我怎么能把这个Json数组解析成c#类吗?
答案 0 :(得分:11)
如果您只是将其反序列化为List<RootObject>
,那么您拥有的JSON将会起作用:
var h = JsonConvert.DeserializeObject<List<RootObject>>(string);
或数组:
var h = JsonConvert.DeserializeObject<RootObject[]>(string);
如果要反序列化ListRoot
,JSON需要如下所示:
{
"status": [
{
"text": "Sample Text",
...
},
{
"text": "Another Sample Text",
...
}
]
}