JSON格式转换

代码1:

引用:System.ServiceModel.Web程序集(系统内置)

JSON格式转换
public static T JSONDecode<T>(string json)
{
    JsonQueryStringConverter converter = new JsonQueryStringConverter();
    return (T) converter.ConvertStringToValue(json, typeof(T));
}
JSON格式转换
JSON格式转换
public static string JSONEncode<T>(T obj)
{
    JsonQueryStringConverter converter = new JsonQueryStringConverter();
    return converter.ConvertValueToString(obj, typeof(T));
}
JSON格式转换

代码2:
引用:System.Text.RegularExpressions; System.Runtime.Serialization.Json;

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;
            }
        }
JSON格式转换

JSON格式转换

上一篇:2.30 准备Windows Server 2012 R2操作系统


下一篇:spring web.xml配置