如下面的例子,很容易看出问题:
如果类本身的无参构造函数, 就添加了一些元素,序列化,再反序列化,会导致元素增加。
如果要避免,必须添加:
new JsonSerializerSettings() { ObjectCreationHandling = ObjectCreationHandling.Replace }文章来源:https://www.toymoban.com/news/detail-686711.html
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; }
}
}
文章来源地址https://www.toymoban.com/news/detail-686711.html
到了这里,关于C#: Json序列化和反序列化,集合为什么多出来一些元素?的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!