一、JSON(JavaScript Object Notation)的简介:
① JSON和XML类似,主要用于存储和传输文本信息,但是和XML相比,JSON更小、更快、更易解析、更易编写与阅读。
② C、Python、C++、Java、PHP、Go等编程语言都支持JSON。
二、JSON语法规则:- myObj ={
- "CommParam":[
- { "SenderID":"2001", "SenderParam":"Chinese" },
- { "SenderID":"2002", "SenderParam":"English" },
- ]
- }
复制代码
- 使用 { } 保存对象,对象是一个无序的键值对集合;
- 数据以键值对的形式存储,每个键后面跟着一个冒号:
- 键值对与键值对之间使用,分隔;
- 使用 [ ] 保存数组,数组可以包含多个对象;
- 键值对中值的类型可以是:
- 数字(整数或浮点数):{ "age" : 20 }
- 字符串(双引号中):{ "name" : "LX" }
- 逻辑值(true或者false):{ "isRotate" : true }
- 数组(在中括号中)
- 对象(在大括号中)
- null:{ "personObject" : null }
三、JSON的使用:
①首先定义Json数据- {
- "name":"json 在线工具",
- "url":"https://www.sojson.com",
- "address":{
- "city":"北京",
- "country":"中国"
- },
- "arrayBrowser":[{
- "name":"Google",
- "url":"http://www.google.com"
- },
- {
- "name":"Baidu",
- "url":"http://www.baidu.com"
- },
- {
- "name":"SoSo",
- "url":"http://www.SoSo.com"
- }]
- }
复制代码 ②可使用工具将JSON生成C#实体:在线JSON转C#实体类,JSON转Java实体类 (sojson.com)- public class Address
- {
- public string city { get; set; }
- public string country { get; set; }
- }
- public class ArrayBrowser
- {
- public string name { get; set; }
- public string url { get; set; }
- }
- public class JSONObject
- {
- public string name { get; set; }
- public string url { get; set; }
- public Address address { get; set; }
- public List<ArrayBrowser> arrayBrowser { get; set; }
- }
复制代码 ③ C#代码解析JSON数据:
—— 第一种:通过JSON结构映射实体类的方式解析JSON数据- using Newtonsoft.Json.Linq;
- using Newtonsoft.Json;
- //将序列化的JSON字符串反序列化,得到JSON对象
- JSONObject JsonObj = (JSONObject)JsonConvert.DeserializeObject(serialzedObject, typeof(JSONObject));
- Console.WriteLine(JsonObj.name);//json 在线工具<br>
复制代码- //将JSON对象序列化成JSON字符串
- string str = JsonConvert.SerializeObject(JsonObject);
- Console.WriteLine(str);<br>
复制代码 ——第二种:不需要创建实体类,直接对Json数据进行解析- using Newtonsoft.Json.Linq
- //将字符串反序列化成JObject类型
- JObject jobj = JObject.Parse(serialzedObject);
- Console.WriteLine(jobj["name"].Tostring());//输出:json 在线工具
- //解析Json中的数组对象
- JArray jarr = JArray.Parse(jobj["arrayBrowser"].ToString());<br>foreach(var j in jarr)<br>{<br> Console.WriteLine(j["name"]);<br>}
- ————————————————————————
- //若想将JObject对象序列化成字符串
- JObject obj = new JObject();
- obj["name"] = "Rose";
- obj["age"] = 23;
- Console.WriteLine(obj.ToString());
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |