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; }
    }
}
相关推荐
我是苏苏4 小时前
WPF开发01:基础控件及常用模板篇
开发语言·c#·html·wpf
BerrySen1785 小时前
现代 C# 全栈与高性能编程实战指南:从 CLR 底层机制到 AI Agent 智能体架构
人工智能·架构·c#
在世修行5 小时前
从零打造 C# 工业视觉检测系统(六):OpenCV 图像处理与像素级比例尺标定
opencv·c#·视觉检测
程序猿小玉兒6 小时前
Quartz定时任务偶尔不执行
服务器·windows·microsoft
小金子会发光15 小时前
C# WinForms 手搓 Modbus RTU 调试助手:不依赖第三方 Modbus 库,从 CRC16 到 8 种功能码完整实现
c#·modbusrtu·串口通讯
上海安当技术19 小时前
C/S 桌面软件怎么接 UKey 强认证?C# SDK 与 C 动态库集成 WinForms/Qt/工控实战
c语言·qt·c#
明如正午21 小时前
【C#】跨线程更新进度条_UpdateProgress 方法解析
c#
曹牧1 天前
C#:`JsonConvert.DeserializeObject`
windows·c#
望天hous1 天前
C#中masstranist快速入门
开发语言·c#
冷咖啡离 我的笨笨1 天前
数据去重:通过 C# 删除 Excel 中的重复行
开发语言·c#·excel