[英]C# - deserialize JSON object
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: 我试图将以下json绑定到一个列表,请注意每个字符串可以包含多个元素,因此列表将如下所示:
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.
谢谢。
The sample JSON contains a list of objects, each an element representing a Shoe
. 示例JSON包含一个对象列表,每个对象都代表一个
Shoe
。 The property representing the collection of colours in the JSON is called shoes
so the class should look like this: 表示JSON中颜色集合的属性称为
shoes
因此类应如下所示:
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);
It looks like your data model is incorrect compared to your JSON. 与您的JSON相比,您的数据模型看起来不正确。 I would suggest going to json2csharp page and pasting JSON there to get the C# generated class
我建议去json2csharp页面并在那里粘贴JSON以获得C#生成的类
I already did that for you: 我已经为你做了这件事:
public class RootObject
{
public List<string> shoes { get; set; }
}
Your C# class is wrong. 你的C#类错了。
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.