Reputation: 63
I am trying to bind the following json to a list, note that each string can contain more than one element, so the list would look like this:
red,black
blue
orange,blue,red,black,pink
[
{
"shoes": [
"red",
"black"
]
},
{
"shoes": [
"blue"
]
},
{
"shoes": [
"orange",
"blue",
"red",
"black",
"pink"
]
}
]
Here is what I have so far, it's not much:
public class Shoes
{
[JsonProperty("colors")]
public IList<string> Colors { get; set; }
}
within main, I am calling the actual link (unfortunately I can't provide it here)
using (WebClient wc = new WebClient())
{
string json = wc.DownloadString(@"JSONlink");
Shoes shoe = JsonConvert.DeserializeObject<Shoes>(json);
}
It gives me the following error:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'xxx' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
I don't have a lot of experience in this area, so any help would be great. Thanks.
Upvotes: 4
Views: 195
Reputation: 5445
The sample JSON contains a list of objects, each an element representing a Shoe
. The property representing the collection of colours in the JSON is called shoes
so the class should look like this:
public class Shoe
{
[JsonProperty("shoes")]
public IList<string> Colors { get; set; }
}
You also need to de-serialize to a collection of shoes not a single instance:
var shoes = JsonConvert.DeserializeObject<List<Shoe>>(json);
Upvotes: 4
Reputation: 4046
Your C# class is wrong.
Use this class :
public class Result
{
public List<string> shoes { get; set; }
}
Deserialization :
using (WebClient wc = new WebClient())
{
string json = wc.DownloadString(@"JSONlink");
var result = JsonConvert.DeserializeObject<List<Result>>(json);
}
Upvotes: 1
Reputation: 4403
It looks like your data model is incorrect compared to your JSON. I would suggest going to json2csharp page and pasting JSON there to get the C# generated class
I already did that for you:
public class RootObject
{
public List<string> shoes { get; set; }
}
Upvotes: 1