简体   繁体   中英

NewtonSoft.Json JsonConvert Deserialize error

I have serialized a complex object( containing abstract classes, read only properties) using Newtonsoft.Jsonconverter SerializeObject successfully. While trying to Deserialize the same using DeserializeObject method, it throws following error - An item with this key has already been added. On further investigation I found out that there might be some properties in the object with same name. But I couldn't find any property name being repeated in json file being de-serialized.

Version of NewtonSoft Json : 8.0.3

Hi I was trying to replicate your error but actually what I got was a successful result. this is the test I did :

using Newtonsoft.Json;
using System;
using System.Collections.Generic;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            var child = new Child();
            var serializesObject = JsonConvert.SerializeObject(child);

            var deserializedObject = JsonConvert.DeserializeObject(serializesObject, typeof(Child));
        }        
    }

    public abstract class Abstract
    {
        public int Prop1 { get; set; }
        public readonly string Prop2;
        public List<string> Prop3 { get; set; }
        public int[] Prop4 { get; set; }

        public abstract void Hey();

        public Abstract()
        {
            Prop1 = 1;
            Prop2 = "2";
            Prop3 = new List<string>();
            Prop4 = new int[4];
        }
    }

    public class Child : Abstract
    {
        public readonly string Prop5;

        public Child()
        {
            Prop5 = "5";

        }
        public override void Hey()
        {
            throw new NotImplementedException();
        }
    }
}

I hope that this code can help you to get to the expected result you want.

Cheers,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM