Json序列化问题

之前Json字符反序列化为C#对象时

总是写一个实体类。。

如:{"a":5,"b":10} 这种json字符串

对应的实体类为:

public class Rootobject
    {
        public int a { get; set; }
        public int b { get; set; }
    }

对应的C#后台代码为:

 string json = "{"a":5,"b":10}"; ({"a":5,"b":10})
Rootobject b = JsonConvert.DeserializeObject<Rootobject>(json);

这样写完全没问题。

可是要是json字符串改为 {"a":5,"1":10}

对应的实体类就要改成

public class Rootobject
    {
        public int a { get; set; }
        public int 1 { get; set; }
    }

属性名为1这种写法会报错的。。。。

两种解决方案:

方案一:

给属性加个Json.net的特性

public class Rootobject
    {
        public int a { get; set; }
        [JsonProperty("1")]
        public int b { get; set; }
    }

方案二:

  var jObject = JObject.Parse(json);
   string t= jObject["a"].ToString();
   string t5 = jObject["1"].ToString();

原文地址:https://www.cnblogs.com/gaocong/p/5069929.html