如何使用DataContractJsonSerializer解析对象列表?

时间:2014-01-09 07:18:36

标签: c# windows-phone windows-phone-7.1 datacontractjsonserializer

如何使用DataContractJsonSerializer序列化对象列表?

当我尝试解析以下json字符串时,我得到了InvalidCastException

  

“[{\” 名称\ “:\” 亚当\”,\ “年龄\”:\ “空\”},{\ “名称\”:\ “詹姆斯\”,\ “年龄\”: \ “空\”}]“

我一直在使用以下助手类。

public class JsonHelper
    {
        public static string JsonSerializer<T>(T t)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream();
            ser.WriteObject(ms, t);
            ms.Position = 0;
            StreamReader sr = new StreamReader(ms);
            string jsonString = sr.ReadToEnd();
            //string jsonString = Encoding.UTF8.GetString(ms.ToArray());
            ms.Close();

            string p = @"\\/Date\((\d+)\+\d+\)\\/";
            MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString);
            Regex reg = new Regex(p);
            jsonString = reg.Replace(jsonString, matchEvaluator);
            return jsonString;            
        }

        public static T JsonDeserialize<T>(string jsonString)
        {
            string p = @"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}";
            MatchEvaluator matchEvaluator = new MatchEvaluator(
                ConvertDateStringToJsonDate);
            Regex reg = new Regex(p);
            jsonString = reg.Replace(jsonString, matchEvaluator);
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));           
            T obj = (T)ser.ReadObject(ms);
            return obj;
        }

        private static string ConvertJsonDateToDateString(Match m)
        {
            string result = string.Empty;
            DateTime dt = new DateTime(1970, 1, 1);
            dt = dt.AddMilliseconds(long.Parse(m.Groups[1].Value));
            dt = dt.ToLocalTime();
            result = dt.ToString("yyyy-MM-dd HH:mm:ss");
            return result;
        }

        private static string ConvertDateStringToJsonDate(Match m)
        {
            string result = string.Empty;
            DateTime dt = DateTime.Parse(m.Groups[0].Value);
            dt = dt.ToUniversalTime();
            TimeSpan ts = dt - DateTime.Parse("1970-01-01");
            result = string.Format("\\/Date({0}+0800)\\/", ts.TotalMilliseconds);
            return result;
        }

    }

0 个答案:

没有答案