JSON文件读取到内存中就是字符串,.NET操作JSON就是生成与解析JSON字符串。
操作JSON通常有以下几种方式:
1. 原始方式:按照JSON字符串自己来解析。
2. 通用方式【★★★★★】:这种方式是使用开源的类库Newtonsoft.Json,使用NuGet进行引用
1.Json字符串普通格式解析(常用)
string jsonText = "{"zone":"海淀","zone_en":"haidian"}"; JObject jo = (JObject)JsonConvert.DeserializeObject(jsonText); string zone = jo["zone"].ToString(); string zone_en = jo["zone_en"].ToString();
其他写法:
int retCode = -1;//返回码,0表示成功,其他表示失败 string returnMessage = string.Empty;//返回消息,对返回码的描述 string jsonStr = "{"RetCode":3,"ReturnMessage":"测试消息"}"; JavaScriptObject jsonObj = JavaScriptConvert.DeserializeObject<JavaScriptObject>(jsonStr); if (jsonObj != null) { if (jsonObj.ContainsKey("RetCode") && jsonObj["RetCode"] != null) { int.TryParse(jsonObj["RetCode"].ToString(), out retCode); } if (jsonObj.ContainsKey("ReturnMessage") && jsonObj["ReturnMessage"] != null) { returnMessage = jsonObj["ReturnMessage"].ToString(); } }
解析Josn列表数据:
public static JArray GetData2JArray(string url, string key) { string jsonData = HttpHelper.HttpGet(url, "", "gb2312"); JObject obj = JObject.Parse(jsonData); return (JArray)obj[key]; }
以上Json的返回的数据:
{"Pictures": [ {"PictureSrc":"http://i.ssimg.cn/ssupload/2016/10/17/707f464645f44b4cb9882b75d23ed8f9.png","PictureLink":"","PictureAlt":"通光线缆 36.50%","PictureTitle":"实盘赛冠军直播室","PictureTitleLink":"132","PictureSummary":"荷塘月色直播室是由野马和荷塘月色夫妻俩共同直播的直播室,野马以短线股为主,荷塘月色以中线股为主,擅于抓涨停板和翻倍牛股。","OrderTime":"2016-10-17 13:16:04"}, {"PictureSrc":"http://i.ssimg.cn/ssupload/2016/10/17/4c38b0a2604e49beaf1e4f7885e6a1a4.png","PictureLink":"","PictureAlt":"天际股份 6.38%","PictureTitle":"证券之星最强王牌播主","PictureTitleLink":"1716","PictureSummary":"深入股海数年,拥有十余年的实战经验。2014年证券之星播主年度冠军,各大一线网站著名博客,多次接受电视台专访。","OrderTime":"2016-10-17 13:12:34"} ] }
解析成自定义实体类列表:
#region 获取手编列表 /// <summary> /// 获取手编列表 /// </summary> /// <returns></returns> public static List<Pictures> GetHandWriteList() { List<Pictures> list = new List<Pictures>(); var data = Common.LiveCastUserManageAPI.GetData2JArray(CmsApiSite, "Pictures"); if (data != null && data.Count > 0) { foreach (var item in data) { Pictures p = new Pictures(); if (!string.IsNullOrEmpty(item["PictureSrc"].ToString())) { p.PictureSrc = item["PictureSrc"].ToString(); } list.Add(p); } } return list; } #endregion
Pictures实体类的定义:
public class Pictures { /// <summary> /// http://i.ssimg.cn/ssupload/2016/10/17/e6500633d4cb4a918c8f45e2c71ab8f6.jpg /// </summary> public string PictureSrc { get; set; } /// <summary> /// /// </summary> public string PictureLink { get; set; } /// <summary> /// 中色股份 53% /// </summary> public string PictureAlt { get; set; } /// <summary> /// 四季度翻倍牛股在哪里? /// </summary> public string PictureTitle { get; set; } /// <summary> /// meihaoxiangwang /// </summary> public string PictureTitleLink { get; set; } /// <summary> /// 荷塘月色直播室是由野马和荷塘月色夫妻俩共同直播的直播室,野马以短线股为主, 荷塘月色以中线股为主,擅于抓涨停板和翻倍牛股。 /// </summary> public string PictureSummary { get; set; } /// <summary> /// 股票名称 /// </summary> public string StockName { get; set; } /// <summary> /// 股票收益率 /// </summary> public string Rate { get; set; } /// <summary> /// 昵称 /// </summary> public string NickName { get; set; } /// <summary> /// 头像 /// </summary> public string HeadImg { get; set; } /// <summary> /// 直播室名称 /// </summary> public string CastRoomName { get; set; } }
JSON生成实体类工具:点击>>
解析JsonArrayList
2.Json字符串嵌套格式解析
string jsonText = "{"beijing":{"zone":"海淀","zone_en":"haidian"}}"; JObject jo = (JObject)JsonConvert.DeserializeObject(jsonText); string zone = jo["beijing"]["zone"].ToString(); string zone_en = jo["beijing"]["zone_en"].ToString();
3.Json字符串数组格式解析
string jsonArrayText = "[{'a':'a1','b':'b1'},{'a':'a2','b':'b2'}]"; //"[{'a':'a1','b':'b1'}]即使只有一个元素,也需要加上[] string jsonArrayText = "[{"a":"a1","b":"b1"},{"a":"a2","b":"b2"}]"; //上面写法和此写法效果一样 JArray jArray = (JArray)JsonConvert.DeserializeObject(jsonArrayText);//jsonArrayText必须是带[]数组格式字符串 string str = jArray[0]["a"].ToString();
/// <summary> /// 将JSON转字符串(包括数组)转为T /// </summary> /// <typeparam name="T"></typeparam> /// <param name="json"></param> /// <returns></returns> public static T JsonConvertObject<T>(string json) { return JsonConvert.DeserializeObject<T>(json); }
备注:
json格式字符串转换为实体类,大括号{}表示对象,[]数组表示列表。