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; }
    }
}
相关推荐
吃一碗粉只付一碗钱9 小时前
12-给SPA友好的401和403响应
c#·状态模式
前端精髓11 小时前
调用大模型API
运维·服务器·microsoft
caimouse16 小时前
MonoDevelop 编译用户应用程序时调用的是哪个编译器
c#
will_net18 小时前
apollo 站点部署&C#接入
开发语言·c#·apollo
老牛日常随笔18 小时前
微软开源Flint Chart:AI画图表总是画不对?让编译器来画,AI只写数据就行
人工智能·microsoft
吾与谁归in1 天前
C#脚本工具,支持智能提示自动补全(WPF + Roslyn + AvalonEdit)
开发语言·c#·wpf
昂好的day1 天前
WPF 从零入门(上):WPF 是什么、XAML 语法、布局与样式全解
开发语言·c#·wpf
GlobalInfo1 天前
2026年机器人多指灵巧手市场分析报告——涵盖行业调查、趋势分析与发展前景
大数据·人工智能·microsoft·微服务·机器人
zzu123zsw1 天前
从臃肿的模板调用到声明式契约:深入 UniHttp 动态代理与多渠道生命周期扩展
java·spring boot·microsoft·unihttp