I would like to build a vb.net app that consumes a JSON REST web service. Following, an example of the data that I receive when calling this service:
[
{"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}
]
I have tried some tools like json2csharp to generate a class from this example but these tools generate a class like this:
public class RootObject
{
public int id { get; set; }
public string title { get; set; }
public string alternative_title { get; set; }
public int year { get; set; }
}
This class ignores the fact that a list is returned from the service. I assume this is caused by the fact that the json output does not start with a root level object.
What would my c#/vb.net class look like for this json output or should it be parsed "manually"?
You can use Json.Net, and deserialize to array:
var result = JsonConvert.DeserializeObject<RootObject[]>(json_string);
I am not sure what the problem is exactly for you. Using Newtonsoft Json.NET, JsonConvert.DeserializeObject<IEnumerable<RootObject>>(input), i.e. this:
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);
produces the following output for me:
17552 - Avatar, (2009)
31586 - Avatar, Cyber Wars (2004)
81644 - Aliens vs. Avatars, (2011)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With