JSON格式转换

代码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;
            }
        }

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。