ToB企服应用市场:ToB评测及商务社交产业平台

标题: 利用C#传输Json数据 [打印本页]

作者: 饭宝    时间: 2022-9-16 17:14
标题: 利用C#传输Json数据
一、JSON(JavaScript Object Notation)的简介:
  ① JSON和XML类似,主要用于存储和传输文本信息,但是和XML相比,JSON更小、更快、更易解析、更易编写与阅读。
  ② C、Python、C++、Java、PHP、Go等编程语言都支持JSON。
二、JSON语法规则:
  1. myObj ={
  2.     "CommParam":[
  3.       { "SenderID":"2001",  "SenderParam":"Chinese" },
  4.       { "SenderID":"2002",  "SenderParam":"English" },
  5.     ]
  6. }  
复制代码
三、JSON的使用:
①首先定义Json数据
  1. {
  2.     "name":"json 在线工具",
  3.     "url":"https://www.sojson.com",
  4.     "address":{
  5.         "city":"北京",
  6.         "country":"中国"
  7.     },
  8.     "arrayBrowser":[{
  9.         "name":"Google",
  10.         "url":"http://www.google.com"
  11.     },
  12.     {
  13.        "name":"Baidu",
  14.        "url":"http://www.baidu.com"
  15.    },
  16.    {
  17.        "name":"SoSo",
  18.        "url":"http://www.SoSo.com"
  19.    }]
  20. }
复制代码
②可使用工具将JSON生成C#实体:在线JSON转C#实体类,JSON转Java实体类 (sojson.com)
  1. public class Address
  2. {
  3.     public string city { get; set; }
  4.     public string country { get; set; }
  5. }
  6. public class ArrayBrowser
  7. {
  8.     public string name { get; set; }
  9.     public string url { get; set; }
  10. }
  11. public class JSONObject
  12. {
  13.     public string name { get; set; }
  14.     public string url { get; set; }
  15.     public Address address { get; set; }
  16.     public List<ArrayBrowser> arrayBrowser { get; set; }
  17. }
复制代码
③ C#代码解析JSON数据:
—— 第一种:通过JSON结构映射实体类的方式解析JSON数据
  1. using Newtonsoft.Json.Linq;
  2. using Newtonsoft.Json;
  3. //将序列化的JSON字符串反序列化,得到JSON对象
  4. JSONObject JsonObj = (JSONObject)JsonConvert.DeserializeObject(serialzedObject, typeof(JSONObject));
  5. Console.WriteLine(JsonObj.name);//json 在线工具<br>
复制代码
  1. ————————————————————————
复制代码
  1. //将JSON对象序列化成JSON字符串
  2. string str = JsonConvert.SerializeObject(JsonObject);
  3. Console.WriteLine(str);<br>
复制代码
 ——第二种:不需要创建实体类,直接对Json数据进行解析
  1. using Newtonsoft.Json.Linq
  2. //将字符串反序列化成JObject类型
  3. JObject jobj = JObject.Parse(serialzedObject);
  4. Console.WriteLine(jobj["name"].Tostring());//输出:json 在线工具
  5. //解析Json中的数组对象
  6. JArray jarr = JArray.Parse(jobj["arrayBrowser"].ToString());<br>foreach(var j in jarr)<br>{<br>  Console.WriteLine(j["name"]);<br>}
  7. ————————————————————————
  8. //若想将JObject对象序列化成字符串
  9. JObject obj = new JObject();
  10. obj["name"] = "Rose";
  11. obj["age"] = 23;
  12. Console.WriteLine(obj.ToString());
复制代码
 

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4