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; }
    }
}
相关推荐
曹牧11 小时前
C#:24小时制时间
c#
唐青枫16 小时前
别急着拆服务:C#.NET 微服务架构从边界设计到实战
c#·.net
czhc114007566320 小时前
从一份运行日志还原一次生产卡死:三个信号与一场“假卡死“
c#
Jazz_z21 小时前
如何用 C# 读取 Word 中的表格数据
开发语言·c#
阿松爱学习1 天前
【Unity开发】FileStream 详解及用法指南
unity·c#·unity开发
淡海水1 天前
12-02-性能-数据结构性能调查案例1-5
数据结构·性能优化·c#
Java的搬运工1 天前
使用 C# 轻松管理 PDF 文件的用户权限
c#·用户权限
Neil20132 天前
ajax跨域请求
c#
唐青枫2 天前
别把 Razor 当成几段 HTML:C#.NET Razor Pages、MVC 视图与实战详解
c#·.net
宝桥南山2 天前
Microsoft Fabric - 简单尝试一下Microsoft Fabric .NET SDK
microsoft·微软·.net·.netcore·powerbi·fabric