英文:
Why does deserialization append to an initialized `List<T>` instead of overwriting it?
问题
我有一个与配置相关的数据模型,要求所有属性都必须具有默认值,以确保正确执行消费操作。以这个非常简单的模型为例:
public class Sample {
public List<int> Integers { get; set; }
public Sample() =>
Integers = new List<int> { 1 };
}
预期该模型至少包含一个值,因此我们基于预定义要求指定默认处理值。然而,该值不必特定为 1
,如果客户端指定不同的值或许多不同的值,我们的处理应该尊重其输入。假设客户端指定以下要反序列化为模型的 json
配置:
{
"integers": [ 2, 3 ]
}
在运行时,我们直接加载配置,但出于这个问题的考虑,让我们使用一个本地的 string
变量:
using Newtonsoft.Json;
...
string configuration = "{\"integers\": [ 2, 3 ] }";
var sample = JsonConvert.DeserializeObject<Sample>(configuration);
Console.WriteLine(string.Join(",", sample.Integers));
上面的代码片段应该产生如下输出:
1,2,3
然而,我的问题是... 为什么反序列化过程会追加到集合而不是覆盖它?
英文:
I have a configuration-related data model which is required to have default values for all properties to ensure proper execution of consuming operations. Take for example this very simple model:
public class Sample {
public List<int> Integers { get; set; }
public Sample() =>
Integers = new List<int> { 1 };
}
This model is expected to contain at least one value so we specify a default processing value based on predefined requirements. However, the value doesn't have to be 1
specifically and if a client specifies a different value or many different values, our process should respect their input. Assume the client specifies the following json
configuration to be deserialized into the model:
{
"integers": [ 2, 3 ]
}
During runtime, we load the configuration directly, but let's use a local string
variable for the sake of this question:
using Newtonsoft.Json
...
string configuration = "{ \"integers\": [ 2, 3 ] }";
var sample = JsonConvert.DeserializeObject<Sample>(configuration);
Console.WriteLine(string.Join(",", sample.Integers));
The above code snippet should produce an output of:
> 1,2,3
As you can see in my screenshot below, that is the case:
However, my question is why... Why does the deserialization process append to the collection instead of overwriting it?
答案1
得分: 1
你可以指出如何反序列化JSON:
var serializerSettings = new JsonSerializerSettings {
ObjectCreationHandling = ObjectCreationHandling.Replace
};
var sample = JsonConvert.DeserializeObject<Sample>(configuration, serializerSettings);
Console.WriteLine(string.Join(",", sample.Integers)); // [2,3]
默认情况下,它是自动的,如果有什么东西,它会尝试添加。
英文:
You can point how to deserialize the json
var serializerSettings = new JsonSerializerSettings {
ObjectCreationHandling = ObjectCreationHandling.Replace};
var sample = JsonConvert.DeserializeObject<Sample>(configuration,serializerSettings);
Console.WriteLine(string.Join(",", sample.Integers)); // [2,3]
by default it is auto, and if there is something it tries to add.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论