C# - JSON操作
Newtonsoft.dll插件
洪大师二次封装:
using System; using System.Collections.Generic; using System.Text; using System.Data; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace DevFramework_2015.Common { public class JsonHelper { public static string ListToJson<T>(List<T> li) #region { string jsonString = ""; jsonString = JsonConvert.SerializeObject(li, Formatting.None); return jsonString; } #endregion public static List<T> JsonToList<T>(string jsonString) #region { List<T> li = JsonConvert.DeserializeObject<List<T>>(jsonString); return li; } #endregion public static string DictionaryToJson<TKey, TValue>(Dictionary<TKey, TValue> dic) #region { string jsonString = ""; jsonString = JsonConvert.SerializeObject(dic, Formatting.None); return jsonString; } #endregion public static Dictionary<TKey, TValue> JsonToDictionary<TKey, TValue>(string jsonString) #region { Dictionary<TKey, TValue> dic = JsonConvert.DeserializeObject<Dictionary<TKey, TValue>>(jsonString); return dic; } #endregion public static string ArrayToJson<T>(T[] arrayObject) #region { string jsonString = ""; jsonString = JsonConvert.SerializeObject(arrayObject, Formatting.None); return jsonString; } #endregion public static T[] JsonToArray<T>(string jsonString) #region { T[] arrayObject = JsonConvert.DeserializeObject<T[]>(jsonString); return arrayObject; } #endregion public static string DataTableToJson(DataTable dt) #region { string jsonString = ""; jsonString = JsonConvert.SerializeObject(dt, Formatting.None); return jsonString; } #endregion public static DataTable JsonToDataTable(string jsonString) #region { DataTable dt; dt = JsonConvert.DeserializeObject<DataTable>(jsonString); return dt; } #endregion } }
对象直接转化为json字符串:
string jsonstr = JsonConvert.SerializeObject(response)
json字符串转化为已知的对象
Response_QueryPrepareInfo _Response_QueryPrepareInfo = JsonConvert.DeserializeObject<Response_QueryPrepareInfo>(sRetStr);