JsonConvert无法解析

时间:2015-07-28 10:04:52

标签: c# json json.net

我之前有一个json字符串它工作正常。现在它在我添加嵌套项时没有解析。我想在c#中解析json数组。这是我的json代码。

{
    "Type": "Hotel",    
    "myArray": [{
        "id": 0,
        "time": ["1", "2"],
        "index": 0,
        "picked": [{
            "id": 1,
            "oc": "1"
        }, {
            "id": 2,
            "oc": "1"
        }]
    }, {
        "id": 1,
        "time": [],
        "index": 1,
        "picked": []
    }, {
        "id": 2,
        "time": [],
        "index": 2,
        "picked": []
    }, {
        "id": 3,
        "time": [],
        "index": 3,
        "picked": []
    }, {
        "id": 4,
        "time": [],
        "index": 4,
        "picked": []
    }, {
        "id": 5,
        "time": [],
        "index": 5,
        "picked": []
    }, {
        "id": 6,
        "time": ["3"],
        "index": 6,
        "picked": [{
            "id": 3,
            "oc": "1"
        }]
    }]
}

我想要这样

JsonConvert.DeserializeObject<MyObject>(abovejsonstring)

任何人帮助我。

当前的类结构是

public class MyObject
    {
        public string Type { get; set; }
        public List<MyArray> myArray { get; set; }
    }

    public class MyArray
    {
        public string id { get; set; }
        public string[] time { get; set; }
        public string index { get; set; }
        public List<Picked> picked { get; set; }
    }
    public class Picked 
    {
        public string id { get; set; }
        public string oc { get; set; }
    }

错误是:

  

无法将当前JSON对象(例如{&#34; name&#34;:&#34; value&#34;})反序列化为类型&#39; System.String []&#39;因为该类型需要JSON数组(例如[1,2,3])才能正确反序列化。要修复此错误,请将JSON更改为JSON数组(例如[1,2,3])或更改反序列化类型,使其成为普通的.NET类型(例如,不是像整数这样的基本类型,而不是类似的集合类型可以从JSON对象反序列化的数组或List。 JsonObjectAttribute也可以添加到类型中以强制它从JSON对象反序列化。

2 个答案:

答案 0 :(得分:0)

我认为问题在于这是牛顿从json看到的结构:

public class MyArray
{
    public int id { get; set; }
    public List<object> time { get; set; }
    public int index { get; set; }
    public List<object> picked { get; set; }
}

所以你应该将数组(string []时间)改为List time

编辑:看到它不是时间阵列,那么可能是因为它没有识别出&#34; Picked&#34;对象

答案 1 :(得分:0)

我试过

http://json2csharp.com/

http://jsonclassgenerator.codeplex.com/

优异。工作

public class WeekArray2
    {

        [JsonProperty("id")]
        public int id { get; set; }

        [JsonProperty("time")]
        public string[] time { get; set; }

        [JsonProperty("index")]
        public int index { get; set; }

        [JsonProperty("picked")]
        public Picked2[] picked { get; set; }
    }


    public class MS
    {

        [JsonProperty("year")]
        public string year { get; set; }

        [JsonProperty("month")]
        public string month { get; set; }

        [JsonProperty("currentmonth")]
        public string currentmonth { get; set; }

        [JsonProperty("community")]
        public string community { get; set; } 

        [JsonProperty("WeekArray")]
        public WeekArray2[] weekarray { get; set; }
    }