Deserializing JSON into an object
I have some JSON:
{
"foo" : [
{ "bar" : "baz" },
{ "bar" : "qux" }
]
}
And I want to deserialize this into a collection. I have 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?
Solution 1:
That JSON is not a Foo
JSON array. The code JsonConvert.DeserializeObject<T>(jsonString)
will parse the JSON string from the root on up, and your type T
must match that JSON structure exactly. The parser is not going to guess which JSON member is supposed to represent the List<Foo>
you're looking for.
You need a root object, that represents the JSON from the root element.
You can easily let the classes to do that be generated from a sample JSON. To do this, copy your JSON and click Edit -> Paste Special -> Paste JSON As Classes
in Visual Studio.
Alternatively, you could do the same on http://json2csharp.com, which generates more or less the same classes.
You'll see that the collection actually is 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 the 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 a JsonProperty
attribute to them:
public class Foo
{
[JsonProperty("bar")]
public string Bar { get; set; }
}
Also make sure that the JSON contains enough sample data. The class parser will have to guess the appropriate C# type based on the contents found in the JSON.