0

How to serialize list of objects using DataContractJsonSerializer?

When I tried to parse the following json string, I got InvalidCastException

"[{\"name\":\"Adam\",\"age\":\"null\"},{\"name\":\"James\",\"age\":\"null\"}]"

I have been using the following helper class.

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

    }
dbc
  • 104,963
  • 20
  • 228
  • 340
karthik
  • 125
  • 1
  • 1
  • 5
  • Have you followed [this example from MSDN](http://msdn.microsoft.com/en-us/library/bb412179(v=vs.110).aspx)? – Neil Turner Jan 09 '14 at 16:21
  • @NeilTurner : Yes, I have followed it. I can't parse only when list of objects are given as json string – karthik Jan 10 '14 at 07:11
  • Your parsing of the JSON String looks overly complex. Where are the objects that the JSON will be de-serialised into? – Neil Turner Jan 10 '14 at 11:38

0 Answers0