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?
That JSON is not a
Foo
JSON array. The codeJsonConvert.DeserializeObject<T>(jsonString)
will parse the JSON string from the root on up, and your typeT
must match that JSON structure exactly. The parser is not going to guess which JSON member is supposed to represent theList<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:
Now you can deserialize the JSON from the root (and be sure to rename
RootObject
to something useful):And access the collection:
You can always rename properties to follow your casing convention and apply a
JsonProperty
attribute to them: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.