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; }
    }
}
相关推荐
鱼听禅2 小时前
C#学习笔记-Entity Framework Core基础操作学习
c#·orm·ef core
Z5998178413 小时前
c#软件开发学习笔记--分组、游标与临时表、分页
笔记·学习·c#
rick9773 小时前
用 C# 从零搭建本地知识库:RAG 系统完整实战
c#
Z5998178414 小时前
c#软件开发学习笔记--事务、索引
笔记·学习·c#
geovindu4 小时前
CSharp: Composite Pattern
开发语言·后端·c#·组合模式·结构型模式
LeoTao4 小时前
C#专题-C# 异常处理
c#
影寂ldy5 小时前
C# 多线程进阶知识点(线程优先级、多委托传参、线程锁、死锁)
开发语言·数据库·c#
wrq14721 小时前
MyAccess 完整使用手册
c#·orm框架
阿里技术1 天前
从 Coder 到 Designer :电商团队数据研发的 Harness Engineering 实践
人工智能·microsoft·机器学习