Removing JSON deserialization into an object

I have a JSON:

{ "foo" : [ { "bar" : "baz" }, { "bar" : "qux" } ] } 

And I want to deserialize this into a collection. I defined this class:

 public class Foo { public string bar { get; set; } } 

However, the following code does not work:

  JsonConvert.DeserializeObject<List<Foo>>(jsonString); 

How can I deserialize my JSON?

+7
json c #
source share
1 answer

That JSON is not an Foo JSON array. The JsonConvert.DeserializeObject<T>(jsonString) will parse the JSON string from root to , and your type T should exactly match this JSON structure. The parser is not going to guess which JSON member should represent the List<Foo> you are looking for.

You need a root object representing JSON from the root element.

You can easily let classes do this with a JSON sample. To do this, copy your JSON and click Edit -> Paste Special -> Paste JSON As Classes in Visual Studio.

Alternatively, you can do the same at http://json2csharp.com , which generates more or less the same classes.

You will see that the collection is actually one element deeper than expected:

 public class Foo { public string bar { get; set; } } public class RootObject { public List<Foo> foo { get; set; } } 

Now you can deserialize JSON from the root (and be sure to rename RootObject to something useful):

 var rootObject = JsonConvert.DeserializeObject<RootObject>(jsonString); 

And access the collection:

 foreach (var foo in rootObject.foo) { // foo is a `Foo` } 

You can always rename properties to follow your casing convention and apply the JsonProperty attribute to them:

 public class Foo { [JsonProperty("bar")] public string Bar { get; set; } } 

Also make sure that JSON contains enough sample data. The class parser should guess the appropriate C # type based on the content contained in JSON.

+17
source share

All Articles