代码1:
引用:System.ServiceModel.Web程序集(系统内置)
public static T JSONDecode<T>(string json) { JsonQueryStringConverter converter = new JsonQueryStringConverter(); return (T) converter.ConvertStringToValue(json, typeof(T)); }
public static string JSONEncode<T>(T obj) { JsonQueryStringConverter converter = new JsonQueryStringConverter(); return converter.ConvertValueToString(obj, typeof(T)); }
代码2:
引用:System.Text.RegularExpressions;
System.Runtime.Serialization.Json;
public static string ObjectToJson<T>(T t) { using (MemoryStream ms = new MemoryStream()) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T)); serializer.WriteObject(ms, t); ms.Position = 0; using (StreamReader reader = new StreamReader(ms)) { string json = reader.ReadToEnd(); string p = @"\\/Date\((\d+)\+\d+\)\\/"; MatchEvaluator evaluator = new MatchEvaluator(ConvertJsonDataToDataString); Regex reg = new Regex(p); json = reg.Replace(json, evaluator); return json; } } } public static T JsonToObject<T>(string json) { string p = @"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}"; MatchEvaluator evaluator = new MatchEvaluator(ConvertDateStringToJsonDate); //对时间进行处理 Regex reg = new Regex(p); json = reg.Replace(json, evaluator); using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json))) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T)); JsonQueryStringConverter json1 = new JsonQueryStringConverter(); return (T)json1.ConvertStringToValue(json, typeof(T)); T data = (T)serializer.ReadObject(ms); return data; } }