C#: Json序列化和反序列化,集合为什么多出来一些元素?

如下面的例子,很容易看出问题:

如果类本身的无参构造函数, 就添加了一些元素,序列化,再反序列化,会导致元素增加。

如果要避免,必须添加:

new JsonSerializerSettings() { ObjectCreationHandling = ObjectCreationHandling.Replace }

cs 复制代码
using Newtonsoft.Json;
using System;
using System.Collections.Generic;

class Program3
{
    static void Main(string[] args)
    {
        Product product = new Product();
        Console.WriteLine("Orginal Count:{0}", product.ListCustomer.Count);
        string json = JsonConvert.SerializeObject(product);  //序列化
        Product result1 = JsonConvert.DeserializeObject<Product>(json);
        Console.WriteLine("Result Count:{0}", result1.ListCustomer.Count);
        Product result2 = JsonConvert.DeserializeObject<Product>(json,
                    new JsonSerializerSettings() { ObjectCreationHandling = ObjectCreationHandling.Replace });
        Console.WriteLine("Result2 Count:{0}", result2.ListCustomer.Count);
        Console.WriteLine("--------------------------------");
        P2 p = new P2();
        p.ListCustomer = new List<int>();
        p.ListCustomer.AddRange(new int[]{ 1,2,3,4 });
        Console.WriteLine("Orginal Count:{0}", p.ListCustomer.Count);
        string json2 = JsonConvert.SerializeObject(p);  //序列化
        P2 p2Result = JsonConvert.DeserializeObject<P2>(json2);
        Console.WriteLine("Result Count:{0}", p2Result.ListCustomer.Count);

        Console.WriteLine("END");
        Console.Read();
    }

    public class Product
    {
        public Product()
        {
            ListCustomer = new List<int> { 1, 2, 3, 4 };
        }
        public List<int> ListCustomer { get; set; }
    }

    public class P2
    {
        public List<int> ListCustomer { get; set; }
    }
}
相关推荐
Scout-leaf4 天前
WPF新手村教程(三)—— 路由事件
c#·wpf
用户298698530144 天前
程序员效率工具:Spire.Doc如何助你一键搞定Word表格排版
后端·c#·.net
mudtools5 天前
搭建一套.net下能落地的飞书考勤系统
后端·c#·.net
玩泥巴的5 天前
搭建一套.net下能落地的飞书考勤系统
c#·.net·二次开发·飞书
唐宋元明清21885 天前
.NET 本地Db数据库-技术方案选型
windows·c#
lindexi5 天前
dotnet DirectX 通过可等待交换链降低输入渲染延迟
c#·directx·d2d·direct2d·vortice
qq_454245035 天前
基于组件与行为的树状节点系统
数据结构·c#
bugcome_com5 天前
C# 类的基础与进阶概念详解
c#
雪人不是菜鸡5 天前
简单工厂模式
开发语言·算法·c#
铸人5 天前
大数分解的Shor算法-C#
开发语言·算法·c#