C#-反序列化JSON对象 [英] C# - deserialize JSON object
问题描述
我正在尝试将以下json绑定到列表,请注意,每个字符串可以包含多个元素,因此列表如下所示:
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:
红色,黑色
蓝色
橙色,蓝色,红色,黑色,粉红色
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; }
}
在main内,我正在调用实际的链接(不幸的是,我无法在此处提供它)
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);
}
它给了我以下错误:
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.
推荐答案
示例JSON包含一个对象列表,每个对象代表一个 Shoe
.表示JSON中颜色集合的属性称为 shoes
,因此该类应如下所示:
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);
这篇关于C#-反序列化JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!