Json.Net PopulateObject 追加列表而不是设置值

Json.Net PopulateObject Appending list rather than setting value(Json.Net PopulateObject 追加列表而不是设置值)
本文介绍了Json.Net PopulateObject 追加列表而不是设置值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 .Net 4.5 中使用 Json.Net,当在以下对象上使用填充对象时,它会使用 json 的内容来增加 List 的值,而不是设置它的值.

I am using Json.Net for .Net 4.5 and when using populate object on the following object it increments the List's with the content of the json rather than setting its value.

Json.Net

JsonConvert.PopulateObject(string, object)

class MySettingSubClass
{
    public List<string> MyStringList1 = new List<string>(){"one", "two", "three"}
}

class MySetting
{
    public string MyString = "MyString";
    public int MyInt = 5;
    public MySettingSubClass MyClassObject = new MySettingSubClass();
    public List<string> MyStringList2 = new List<string>{"one", "two", "three"};
}

当它们最初加载时,一切都是正确的,但是从 JSON 重新加载两个 MyStringLists 都是重复的 one"、two"、three"、one"、two"、three"

When they initially load, all is correct, however reloading from JSON both MyStringLists are duplicated "one", "two", "three", "one", "two", "three"

推荐答案

你应该告诉 Json.Net 替换数组,像这样:

You should tell Json.Net to replace the arrays, like this:

var serializerSettings = new JsonSerializerSettings {ObjectCreationHandling = ObjectCreationHandling.Replace};


JsonConvert.PopulateObject(jasonString, myObject, serializerSettings)

这篇关于Json.Net PopulateObject 追加列表而不是设置值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)