c# - How to avoid JsonConvert.PopulateObject enqueue on lists
问题描述
I have this silly class:
public class Person
{
public string Name { get; set; }
public string Surname { get; set; }
public int Age { get; set; }
public List<int> NumbersList { get; set; }
}
And I have this two jsons (the second one coming out from a conditional serialization trough ShouldSerialize)
var json1 = "{\"Name\":\"Joe\",\"Surname\":\"Satriani\",\"Age\":40,\"NumbersList\":[10,20,30]}";
var json2= "{\"Name\":\"Mike\",\"NumbersList\":[40,50,60]}";
Also, I have a silly class to display the results:
private void showResult(object theClass)
{
var result = JsonConvert.SerializeObject(theClass);
Debug.WriteLine("result: " + result);
}
Now, I create a class with the first json:
var myPerson = JsonConvert.DeserializeObject<Person>(json1);
And everything is fine: the class gets all the values it should:
showResult(myPerson);
result: {"Name":"Joe","Surname":"Satriani","Age":40,"NumbersList":[10,20,30]}
Now, I want to apply the second json to the already existing class instance:
JsonConvert.PopulateObject(json2, myPerson);
But... this is what I get:
showResult(myPerson);
result: {"Name":"Mike","Surname":"Satriani","Age":40,"NumbersList":[10,20,30,40,50,60]}
So, as far as I understand, the PopulateObject correctly rewrites, as expected, the standard field properties (because I don't get "JoeMike" as Name, I get only "Mike" and this if fine), however, it appends list/indexed ones, because I don't obtain "40,50,60" but "10,20,30,40,50,60"...
So, my question is: is there a way to avoid PopulateObject to deliberately append List/Index/Enumerable objects ?
解决方案
In the JsonSerializerSettings
class, set the ObjectCreationHandling
value to ObjectCreationHandling.Replace
. With this setting, the information is no longer appended but copied.
JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings()
{
ObjectCreationHandling = ObjectCreationHandling.Replace
};
JsonConvert.PopulateObject(json2, myPerson, jsonSerializerSettings);
推荐阅读
- linux - 如何阻止“是”命令重复其他命令?
- c# - Microsoft Azure 中托管的 .NET CORE API 应用程序超时异常(Redis 缓存、SQL、.NET Core)
- apache-spark - Simba Spark JDBC 驱动程序 - DatabaseMetaData.getColumns() 不起作用
- python - 熊猫数据帧中时间戳之间的时间差作为直方图
- maven - 故障安全错误:使用阴影插件时“清单主要属性的签名文件摘要无效”
- delphi - Delphi TCriticalSection Acquire vs Enter - 有什么区别?
- python - 在有 N 个键的迷宫中,我应该怎么做才能找到 BFS 的最短路径?
- kotlin - 你能帮我解释一下这个功能是如何工作的吗?它使用 Inline、reified、valueOf() 和 enumValues
- c++ - 如何在安装期间将文件夹共享访问权限设置为 MSI 中当前登录的用户(或任何其他本地用户)?
- c++ - 为什么我不能将列表初始化用于具有继承的结构?