using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization.Json; using System.Text; using System.Web.Script.Serialization; namespace HS.Common.Helper { public class JsonHelper { //定义一个用于保存静态变量的实例 private static JsonHelper instance = null; //定义一个保证线程同步的标识 private static readonly object locker = new object(); //构造函数为私有,使外界不能创建该类的实例 private JsonHelper() { } public static JsonHelper Instance { get { if (instance == null) { lock (locker) { if (instance == null) instance = new JsonHelper(); } } return instance; } } public string GetJsonValue(string json, string levelOne) { JObject jsonObj = JObject.Parse(json); return jsonObj.GetValue(levelOne).ToString(); } public string GetJsonValue(string json, string levelOne, string levelTwo) { JObject jsonObj = JObject.Parse(json); return jsonObj[levelOne][levelTwo].ToString(); } public string SetJsonValue(string json, string levelOne, string value="") { JObject jsonObj = JObject.Parse(json); jsonObj[levelOne] = value; return jsonObj.ToString(); } public string SetJsonValue(string json, string levelOne, string levelTwo, string value="") { JObject jsonObj = JObject.Parse(json); jsonObj[levelOne][levelTwo] = value; return jsonObj.ToString(); } /// <summary> /// 压缩转义 /// </summary> /// <param name="json"></param> /// <returns></returns> public string CompressEscape(string json) { if (string.IsNullOrEmpty(json)) return string.Empty; return JsonConvert.SerializeObject(json); } /// <summary> /// 格式化json /// </summary> /// <param name="json"></param> /// <returns></returns> public string FormatJsonByStr(string json) { if (string.IsNullOrEmpty(json)) return string.Empty; Object jsonObject = JsonConvert.DeserializeObject(json); return JsonConvert.SerializeObject(jsonObject, Formatting.Indented); } /// <summary> /// 删除转义 /// </summary> /// <param name="json"></param> /// <returns></returns> public string DelEscape(string json) { if (string.IsNullOrEmpty(json)) return string.Empty; // 将JSON字符串解析为C#对象 return JsonConvert.DeserializeObject<object>(json).ToString(); } public string StortJson(string json) { var dic = JsonConvert.DeserializeObject<SortedDictionary<string, object>>(json); SortedDictionary<string, object> keyValues = new SortedDictionary<string, object>(dic); keyValues.OrderBy(m => m.Key);//升序 把Key换成Value 就是对Value进行排序 //keyValues.OrderByDescending(m => m.Key);//降序 return JsonConvert.SerializeObject(keyValues); } /// <summary> /// 转换Dic 到Json /// </summary> /// <param name="dic"></param> /// <returns></returns> public string ConvertDicToJson(Dictionary<string, string> dic) { JObject json = new JObject(); foreach (var item in dic.Keys) { json.Add(item, dic[item]); } return JsonConvert.SerializeObject(json, Formatting.Indented); } public string GetJson(object obj) { if (obj == null) return ""; DataContractJsonSerializer json = new DataContractJsonSerializer(obj.GetType()); using (MemoryStream stream = new MemoryStream()) { json.WriteObject(stream, obj); string szJson = Encoding.UTF8.GetString(stream.ToArray()); return szJson; } } // 从一个对象信息生成Json串 public string ObjectToJson(object obj) { return JsonConvert.SerializeObject(obj); } // 从一个Json串生成对象信息 public object JsonToObject(string jsonString, object obj) { return JsonConvert.DeserializeObject(jsonString, obj.GetType()); } public T Deserialize<T>(string json) { T obj = Activator.CreateInstance<T>(); using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json))) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType()); return (T)serializer.ReadObject(ms); } } public List<T> JsonStringToList<T>(string jsonStr) { JavaScriptSerializer Serializer = new JavaScriptSerializer(); List<T> objs = Serializer.Deserialize<List<T>>(jsonStr); return objs; } public bool IsValidJson(string strInput) { if (string.IsNullOrWhiteSpace(strInput)) { return false; } strInput = strInput.Trim(); while (strInput.StartsWith(@"\") || strInput.StartsWith("'") || strInput.StartsWith("\"")) { strInput = strInput.Substring(1); } while (strInput.EndsWith(@"\") || strInput.EndsWith("'") || strInput.EndsWith("\"")) { strInput = strInput.Substring(0, strInput.Length - 1); } try { var obj = JsonConvert.DeserializeObject(strInput); return true; } catch { return false; } } } }
部分接口应用示例:
using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Demos { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnFormat_Click(object sender, EventArgs e) { string json = "{\"infcode\":\"0\",\"inf_refmsgid\":\"H61011600330202409180855405628\",\"recer_sys_code\":\"GXYTH \",\"refmsg_time\":\"20200730123541\",\"respond_time\":\"20200730123539\",\"err_msg\":\"\",\"warn_msg\":\"\",\"sign_no\":\"800600044\",\"output\":{\"orgCode\":\"1120\",\"orgName\":\"协议机构名称\",\"adm_time\":\"入院时间\",\"dscg_time\":\"出院日期\",\"dscg_trt_rslt\":\"出院原因\",\"diag_code\":\"出院诊断疾病编 码\",\"med_type\":\"11\",\"medfee_sumamt\":\"100\",\"setl_time\":\"20240912151515\",\"ipt_otp_no\":\"门诊/住院流水号\",\"medrcdno\":\"单据号\",\"inhosp_stas\":\"0\",\"msgid\":\"发送方报文 ID\"}}"; JObject jsonObj = JObject.Parse(json); string str = GetJsonValue(json, "infcode"); string str2 = GetJsonValue(json, "output", "dscg_time"); this.txtJson.Text = str + str2; this.txtFormatJson.Text = SetJsonValue(json, "output", "dscg_time", "测试修改指定节点内容"); } public string GetJsonValue(string json, string levelOne) { JObject jsonObj = JObject.Parse(json); return jsonObj.GetValue(levelOne).ToString(); } public string GetJsonValue(string json, string levelOne, string levelTwo) { JObject jsonObj = JObject.Parse(json); return jsonObj[levelOne][levelTwo].ToString(); } public string SetJsonValue(string json, string levelOne, string value="") { JObject jsonObj = JObject.Parse(json); jsonObj[levelOne] = value; return jsonObj.ToString(); } public string SetJsonValue(string json, string levelOne, string levelTwo, string value="") { JObject jsonObj = JObject.Parse(json); jsonObj[levelOne][levelTwo] = value; return jsonObj.ToString(); } } }
补充信息:
/// <summary> /// 获取json指定属性值 /// </summary> /// <param name="json">json信息</param> /// <param name="levelArr">层级|最多5级</param> /// <returns></returns> public string GetJsonValue(string json, params string[] levelArr) { string value = string.Empty; JObject jsonObj = JObject.Parse(json); if (levelArr.Length == 1) value = jsonObj.GetValue(levelArr[0]).ToString(); if (levelArr.Length == 2) value = jsonObj[levelArr[0]][levelArr[1]].ToString(); if (levelArr.Length == 3) value = jsonObj[levelArr[0]][levelArr[1]][levelArr[2]].ToString(); if (levelArr.Length == 4) value = jsonObj[levelArr[0]][levelArr[1]][levelArr[2]][levelArr[3]].ToString(); if (levelArr.Length == 5) value = jsonObj[levelArr[0]][levelArr[1]][levelArr[2]][levelArr[3]][levelArr[4]].ToString(); return value; }
应用方式:
List<string> arr = new List<string>(); arr.Add("output"); arr.Add("ipt_otp_no"); this.txtThree.Text = GetJsonValue(json,arr.ToArray());
博客内容主要用于日常学习记录,内容比较随意,如有问题,还需谅解!!!