Newtonsoft.Json 解析时 导致 List 增加的bug

测试用例

    public class Child
    {
        public int a = 1;
    }

    public class Parent
    {
        private List<Child> _Children = new List<Child>() { new Child() };
        public List<Child> Children
        {
            get
            {
                return _Children;
            }
            set
            {
                _Children = value;
            }
        }
    }
    class TestClass
    {
        public static void Test()
        {
            var parent = new Parent
            {
                Children = new List<Child>{ new Child() }
            };

            var serializedParent = JsonConvert.SerializeObject(parent);
            var deserializedParent = JsonConvert.DeserializeObject<Parent>(serializedParent);
            var reserializedParent = JsonConvert.SerializeObject(deserializedParent);
            
            Console.WriteLine(serializedParent); // {"Children":[{"a":1}]}
            Console.WriteLine(reserializedParent); // {"Children":[{"a":1},{"a":1}]}
        }
    }

解决方案

JsonSerializerSettings settings = new JsonSerializerSettings();
settings.ObjectCreationHandling = ObjectCreationHandling.Replace; // 用替换代替默认的处理
JsonConvert.DeserializeObject<Parent>(serializedParent, settings);

来源

来源

posted @ 2023-07-21 11:07  _NKi  阅读(66)  评论(0编辑  收藏  举报