8

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?

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
CodeCaster
  • 147,647
  • 23
  • 218
  • 272
  • 2
    This is meant as a canonical question for _"Why doesn't this deserialization work"_, and supposed to show a general workflow people could follow. Feel free to answer, improve and use as a duplicate target. – CodeCaster Dec 11 '15 at 11:33

1 Answers1

22

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.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
  • Thank you @CodeCaster. Though I couldn't find the paste special option in VS2010 nor VS2017, the provided link did the job. Wow. Wish I'd known about this site earlier on. THANK YOU! – err1 Aug 29 '17 at 13:12