如何反序列化这个json数据?

时间:2016-08-01 11:13:01

标签: c# json

我有JSON数据。我使用Newtonsoft.Json进行反序列化

{
    {
        "id":"951357",
        "name":"Test Name",
        "hometown":
        {
            "id":"12345",
            "name":"city"
        },

        "bff": [
            {
                "people": {
                    "id":"123789",
                    "name":"People Name"
                },              

                "id":"147369"
            }
        ],

    }
}

我创建了类:

 public class Data
{
    [JsonProperty("id")]
    public string Id;

    [JsonProperty("name")]
    public string Name;

    [JsonProperty("hometown")]
    public string[] Hometown;

    [JsonProperty("bff")]
    public Bff[] Bff;
}

public class Bff
{
    [JsonProperty("people")]
    public People[] People;

    [JsonProperty("id")]
    public string Id;
}

public class People
{
    [JsonProperty("id")]
    public string Id;

    [JsonProperty("name")]
    public string Namel
}

public class Hometown
{
    [JsonProperty("id")]
    public int Id;

    [JsonProperty("name")]
    public string Name;
}

但是如果我打电话的话 Data datatest = JsonConvert.DeserializeObject<Data>(data); 在哪里&#34;数据&#34;它的json数组我有这个错误:

  

最佳重载方法匹配   &#39; Newtonsoft.Json.JsonConvert.DeserializeObject(字符串)&#39;有一些   无效的参数

如果您需要更多信息,请与我们联系。

1 个答案:

答案 0 :(得分:2)

问题在于:

"hometown":
{
    "id":"12345",
    "name":"city"
},

在映射类期望数组时传递单个对象:

[JsonProperty("hometown")]
public string[] Hometown;

执行:

"hometown":
[{
    "id":"12345",
    "name":"city"
}],

另外:

  1. 同样的问题是没有将其作为[]
  2. 的数组People传递
  3. 拥有Hometown类型的string[]属性,而不是Hometowm[]
  4. 你的json
  5. 周围设置了{}

    这是有效的JSON:

    {
        "id":"951357",
        "name":"Test Name",
        "hometown": [{
            "id":"12345",
            "name":"city"
            }],
    
        "bff": [{
            "people": [{
                "id":"123789",
                "name":"People Name"
            }],
            "id":"147369"
        }],
    }
    

    有效代码:

    public class Data
    {
        [JsonProperty("id")]
        public string Id;
        [JsonProperty("name")]
        public string Name;
        [JsonProperty("hometown")]
        public Hometown[] Hometown;
        [JsonProperty("bff")]
        public Bff[] Bff;
    }
    
    public class Bff
    {
        [JsonProperty("people")]
        public People[] People;
        [JsonProperty("id")]
        public string Id;
    }
    
    public class People
    {
        [JsonProperty("id")]
        public string Id;
        [JsonProperty("name")]
        public string Name;
    }
    
    public class Hometown
    {
        [JsonProperty("id")]
        public int Id;
        [JsonProperty("name")]
        public string Name;
    }