.NET Json反序列化处理
最近换工作了 从客户端转到Web端 第一个任务就是去别人的页面上抓取数据 用到的是JSON 因为他们网站json的格式有点怪 所以 就在JSON反序列化上面 花了一点时间
首先用到的工具是http://www.newtonsoft.com/json(记得引入 using Newtonsoft.Json)
然后 根据JSON创建对应的对象类
最后反序列化打回前台就可以用啦
总结三步:引入-根据json结构创建对象类-反序列化成json
下面分三种JSON形式
Demo1:
JsonStr: "{\"Name\":\"Coffee swirl\",\"Content\":\"the json\"}"
这个是最常见的json格式
对象类:
public class demo1 { public string Name { get; set; } public string Content { get; set; } }
输出:
string jsonStr= "{\"Name\":\"Coffee swirl\",\"Content\":\"the json\"}"; var demo = JsonConvert.DeserializeObject<demo1>(jsonStr); label1.Text = demo.Name;
Demo2:
json: "{\"List\":[{\"Name\":\"aaa\"},{\"Name\":\"bbb\"},{\"Name\":\"ccc\"}]}"
注意list后面带的是[] ,这表示这是个带数组的json格式
对象类:
public class demo2 { public List[] List { get; set; } } public class List { public string Name { get; set; } }
输出:
string json = "{\"List\":[{\"Name\":\"aaa\"},{\"Name\":\"bbb\"},{\"Name\":\"ccc\"}]}"; var demo = JsonConvert.DeserializeObject<demo2>(jsonStr); string lab = ""; foreach (var d in demo.List) { lab += d.Name + " "; } label1.Text = lab;
Demo3:
还有一种数组类型:
Json: "[{\"Name\":\"aaa\"},{\"Name\":\"bbb\"},{\"Name\":\"ccc\"}]"
对象类:
public class demo3 { public string Name { get; set; } }
输出:
var demo = JsonConvert.DeserializeObject<demo3[]>(json); string lab = ""; foreach (var d in demo) { lab += d.Name + " "; } label1.Text = lab;
Demo4:
json:(这个是通过在线格式化工具格式化了一下 这样看起来更加清楚)
[
{
"department": {"leader": "x1","number": "10"},
"worker": [
{"id": "1","name": "aaa1","work": "aaa2"},
{"id": "2","name": "bbb1","work": "bbb2"},
{"id": "3","name": "ccc1","work": "ccc2"}
]
},
{
"department": {"leader": "x2","number": "20"},
"worker": [
{"id": "4","name": "ddd1","work": "ddd2"},
{"id": "5","name": "eee1","work": "eee2"},
{"id": "6","name": "fff1","work": "fff2"}
]
}
]
这是个多层嵌套并且带数组的json格式,也是我遇到的比较复杂的一种
对象类:
public class demo4 { public department department { get; set; } public worker[] worker { get; set; } } public class department { public string leader { get; set; } public string number { get; set; } } public class worker { public int id { get; set; } public string name { get; set; } public string work { get; set; } }
输出:
string jsonStr = "[{\"department\": {\"leader\": \"x1\",\"number\": \"10\"},\"worker\": [{\"id\": \"1\",\"name\": \"aaa1\",\"work\": \"aaa2\"},{\"id\": \"2\",\"name\": \"bbb1\",\"work\": \"bbb2\"},{\"id\": \"3\",\"name\": \"ccc1\",\"work\": \"ccc2\"}]},{\"department\": {\"leader\": \"x1\",\"number\": \"10\"},\"worker\": [{\"id\":\"4\",\"name\": \"ddd1\",\"work\": \"ddd2\"},{\"id\": \"5\",\"name\": \"eee1\",\"work\": \"eee2\"},{\"id\": \"6\",\"name\": \"fff1\",\"work\": \"fff2\"}]}]"; var demo = JsonConvert.DeserializeObject<demo4[]>(jsonStr); string lab = ""; foreach (var d in demo) { lab += "领导:" + d.department.leader + "组员:{"; foreach (var w in d.worker) { lab += " " + w.name; } lab += "}"; } label1.Text = lab;
基本就是这样了 可能以后遇到其他类型的json 我还会补全 代码都全部验证无误