1

Closed

Generic List member deserialize error

description

I found that generic List member cannot be deserialized correctly in current release(Json.NET 4.5 Release 11). Example code is as follow.
        class Product
        {
            public List<int> Ints = new List<int> { 1, 2 };
            public int[] Ints2 = new int[] { 1, 2 };
        }

        private static void testJson()
        {
            // Input: Ints: {1,2} , Ints2: {1,2}
            Product prod = new Product();
            // txt: {"Ints":[1,2],"Ints2":[1,2]}
            string txt = Newtonsoft.Json.JsonConvert.SerializeObject(prod);
            // Result: Ints: {1,2,1,2} , Ints2: {1,2}
            Product prod2 = Newtonsoft.Json.JsonConvert.DeserializeObject<Product>(txt);
        }
Closed Apr 5, 2013 at 9:06 PM by JamesNK
Use ObjectCreationHandling.Replace

comments

reziarfg wrote Apr 9, 2013 at 12:39 PM

Thanks, it works.
Newtonsoft.Json.JsonSerializer json = new Newtonsoft.Json.JsonSerializer();
json.ObjectCreationHandling = ObjectCreationHandling.Replace;
StringWriter sw = new StringWriter();
Newtonsoft.Json.JsonTextWriter writer = new JsonTextWriter(sw);
json.Serialize(writer, prod);
txt = sw.ToString();

StringReader sr = new StringReader(txt);
// OK
Product prod3 = json.Deserialize(sr,typeof(Product)) as Product;