利用C#传输Json数据

饭宝  金牌会员 | 2022-9-16 17:14:22 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 907|帖子 907|积分 2721

一、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. }  
复制代码

  • 使用 { } 保存对象,对象是一个无序的键值对集合;
  • 数据以键值对的形式存储,每个键后面跟着一个冒号:
  • 键值对与键值对之间使用,分隔;
  • 使用 [ ] 保存数组,数组可以包含多个对象;
  • 键值对中值的类型可以是:

    • 数字(整数或浮点数):{ "age" : 20 }
    • 字符串(双引号中):{ "name" : "LX" }
    • 逻辑值(true或者false):{ "isRotate" : true }
    • 数组(在中括号中)
    • 对象(在大括号中)
    • null:{ "personObject" : null }

三、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());
复制代码
 

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

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

饭宝

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表