我想构建一个使用JSON REST Web服务的vb.net应用程序。下面是我在调用此服务时收到的数据示例:
[
{"id":17552,"title":"Avatar","alternative_title":null,"year":2009},
{"id":31586,"title":"Avatar","alternative_title":"Cyber Wars","year":2004},
{"id":81644,"title":"Aliens vs. Avatars","alternative_title":null,"year":2011}
]
我尝试过一些像json2csharp这样的工具来生成这个例子中的类,但是这些工具生成了这样一个类:
public class RootObject
{
public int id { get; set; }
public string title { get; set; }
public string alternative_title { get; set; }
public int year { get; set; }
}
此类忽略从服务返回列表的事实。我假设这是由于json输出不是以根级对象开始的。
我的c#/ vb.net类对于这个json输出会是什么样的,还是应该“手动”解析?
答案 0 :(得分:2)
我不确定问题究竟是什么。使用Newtonsoft Json.NET,JsonConvert.DeserializeObject<IEnumerable<RootObject>>(input)
,即:
var s = "[{\"id\":17552,\"title\":\"Avatar\",\"alternative_title\":null,\"year\":2009}," +
"{\"id\":31586,\"title\":\"Avatar\",\"alternative_title\":\"Cyber Wars\",\"year\":2004}," +
"{\"id\":81644,\"title\":\"Aliens vs. Avatars\",\"alternative_title\":null,\"year\":2011}]";
var result = JsonConvert.DeserializeObject<IEnumerable<RootObject>>(s);
foreach (var r in result)
Console.WriteLine("{0} - {1}, {2} ({3})", r.id, r.title, r.alternative_title, r.year);
为我生成以下输出:
17552 - Avatar, (2009)
31586 - Avatar, Cyber Wars (2004)
81644 - Aliens vs. Avatars, (2011)
答案 1 :(得分:1)
您可以使用Json.Net,并反序列化为数组:
var result = JsonConvert.DeserializeObject<RootObject[]>(json_string);