利用C#传输Json数据
一、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 在线工具
————————————————————————
//将JSON对象序列化成JSON字符串 string str = JsonConvert.SerializeObject(JsonObject); Console.WriteLine(str);
——第二种:不需要创建实体类,直接对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());
foreach(var j in jarr)
{
Console.WriteLine(j["name"]);
} ———————————————————————— //若想将JObject对象序列化成字符串 JObject obj = new JObject(); obj["name"] = "Rose"; obj["age"] = 23; Console.WriteLine(obj.ToString());
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)