Deserializing nested arrays

Jul 11, 2012 at 4:11 AM

string JSONString = "{
	"property1":"value1",
	"property2":"value2",
	"bars":{
		"items":[
			{
				"bar_property1":"bar_value1",
				"bar_property2":"bar_value2"}
		]
	}
}"

The above is my JSON snippet.

I've created a C# classes for "Foo" and "Bar" like so:

 

public class Foo {
    public string property1 { get; set; }
    public string property2 { get; set; }
    public List<Bar> Bars{ get; set; }
}

public class Bar {
    public string bar_property1 { get; set; }
    public string bar_property2 { get; set; }
}

But, when I call:
Foo myFoo= JsonConvert.DeserializeObject<Foo>(JSONString);

I get the following error:

{"Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into  type 'System.Collections.Generic.List`1[Bar]' because the type requires a  JSON array (e.g. [1,2,3]) to deserialize correctly.\r\nTo fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized  type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a  JSON object.  JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.\r\nPath 'bars.items', line 1, position 70."}

Dec 14, 2012 at 2:29 PM

I have the exact same problem.

Jan 14, 2015 at 11:28 PM
I know this is old and I'm sure you've figured it out in the 2+ years since this post but your Foo class doesn't contain a list of Bar objects (based on your JSON), it's a class with a list of Items. Here's the updated classes that will deserialize correctly:
public class Foo
{
    public string property1 { get; set; }
    public string property2 { get; set; }
    public Bars bars { get; set; }
}

public class Bars
{
    public List<Item> items { get; set; }
}

public class Item
{
    public string bar_property1 { get; set; }
    public string bar_property2 { get; set; }
}
Hope that helps.
Feb 23, 2015 at 9:42 AM
Do a paste special of your JSON data in Visual Studio it will get you the class.