Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

deserialize json without root object to c#/vb.net class

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"?

like image 867
Mark Avatar asked Apr 15 '26 09:04

Mark


2 Answers

You can use Json.Net, and deserialize to array:

var result = JsonConvert.DeserializeObject<RootObject[]>(json_string);
like image 137
Nguyen Kien Avatar answered Apr 16 '26 23:04

Nguyen Kien


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)
like image 37
Alex Avatar answered Apr 16 '26 22:04

Alex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!