Json序列化问题

来源:互联网 发布:营销数据总结报告 编辑:程序博客网 时间:2024/05/20 20:05

在工作当中经常会碰到拿到一段Json字符串需要将这Json字符串反序列化成为一个对象,经常用的方法就是先写一个实体类,如

string json_str="{\"a\":\"5\",\"b\":\"10\"}" 

这种Json串对应的实体类为:

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

反序列化的代码为:

Rootobject b = JsonConvert.DeserializeObject<Rootobject>(json_str)

这样写完全没问题。

可是要是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_str);   string v1= jObject["a"].ToString();   string v2= jObject["1"].ToString();


0 0
原创粉丝点击