反序列化JSON时遇到Null

时间:2015-11-30 14:33:15

标签: c# json

我有json消息

{"code":200,
"description":{
 "15":{"id":"15","name":"US"},
 "25":{"id":"25","name":"Canada"},
 "msg":"Ok"}}

我试图用这样的类反序列化它

public class NewCountry
{
    public string id { get; set; }
    public string name { get; set; }
}

public class NewCountryDescription
{
    public List<NewCountry> Countries{ get; set; }
    public string msg { get; set; }
}

public class RootObject
{
    public int code { get; set; }
    public NewCountryDescription description { get; set; }
}

var ListOfCountries = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(res);

但我总是在NewCountry无效我的错误?

2 个答案:

答案 0 :(得分:2)

如果从json中删除msg或将其移到其他地方(不在descrition中),它将起作用:

    {"code":200,
"description":{
 "15":{"id":"15","name":"US"},
 "25":{"id":"25","name":"Canada"}
 }}


    public class RootObject
    {
        public int code { get; set; }
        public Dictionary<string, NewCountry> description { get; set; }
    }

    public class NewCountry
    {
        public string id { get; set; }
        public string name { get; set; }
    }

答案 1 :(得分:2)

您没有可解析的集合,因此您可以使用JObject和动态或键/值访问。

        var result = JObject.Parse(res);
        var description = (result["description"] as JObject);

        if (description != null)
        {
            var root = new RootObject
            {
                code = (int)result["code"],
                description = new NewCountryDescription
                {
                    msg = description["msg"].ToString(),
                    Countries = (from prop in description.Properties()
                                 where prop.Name != "msg"
                                 select new NewCountry
                                 {
                                     id = prop.Value["id"].ToString(),
                                     name = prop.Value["name"].ToString()
                                 }).ToList()
                }
            };

            Console.Write(root);
        }
相关问题