我解析了这个单独的Json:
{ "text": "Sample Text","id": 123456789,"user": { "name": "ExampleUser","id": 123,"screen_name": "ExampleUser" },"in_reply_to_screen_name": null,}
到我的c#class 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",},{ "text": "Another Sample Text","id": 101112131415,"user": { "name": "ExampleUser2","id": 124,"screen_name": "ExampleUser2" },} ]
我创建另一个类:
public class ListRoot { public List<RootObject> status { get; set; } }
然后使用相同的方法:
ListRoot h = JsonConvert.DeserializeObject<ListRootObject>(string);
但它不起作用.你知道我怎么能把这个Json数组解析成c#类吗?
解决方法
如果您只是将其反序列化为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",... } ] }