为什么当我使用 JSON.NET 反序列化时会忽略我的默认值?

1

本文介绍了为什么当我使用 JSON.NET 反序列化时会忽略我的默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我使用 JSON.NET 作为我的主要序列化程序.

I'm using JSON.NET as my main serializer.

这是我的模型,看我设置了一些 JSONProperties 和一个 DefaultValue.

This is my model, look that I've setted some JSONProperties and a DefaultValue.

public class AssignmentContentItem
{
    [JsonProperty("Id")]
    public string Id { get; set; }
    [JsonProperty("Qty")]
    [DefaultValue(1)]
    public int Quantity { get; set; }
}

当我序列化一个 List 时,它做得很好:

When I serialize a List<AssignmentContentItem>, it doing a good work:

private static JsonSerializerSettings s = new JsonSerializerSettings
{
    DefaultValueHandling = DefaultValueHandling.Ignore,
    NullValueHandling = NullValueHandling.Ignore
};

输出:

[{"Id":"Q0"},{"Id":"Q4"},{"Id":"Q7"}]

但是当我想反序列化这个 jsonContent 时,属性 Qty 总是 0 并且没有设置为默认值.我的意思是,当我反序列化 jsonContent 时,数量的 DefaultValue 应该是 1 而不是 0.

But when I'd like to deserialize this jsonContent, the property Qty is always 0 and is not set to the default value. I mean, when I deserialize that jsonContent, as DefaultValue for Quantity should be one instead of 0.

public static List<AssignmentContentItem> DeserializeAssignmentContent(string jsonContent)
{
    return JsonConvert.DeserializeObject<List<AssignmentContentItem>>(jsonContent, s);
}

我该怎么办

推荐答案

DefaultValue 属性没有设置属性的值.看到这个问题:.NET DefaultValue 属性

The DefaultValue attribute does not set the value of the property. See this question: .NET DefaultValue attribute

最好在构造函数中设置值:

What you might be better off doing is setting the value in the constructor:

public class AssignmentContentItem
{
    [JsonProperty("Id")]
    public string Id { get; set; }
    [JsonProperty("Qty")]
    public int Quantity { get; set; }

    public AssignmentContentItem()
    {
        this.Quantity = 1;
    }
}

这一行在哪里:

AssignmentContentItem item =
    JsonConvert.DeserializeObject<AssignmentContentItem>("{"Id":"Q0"}");

导致 AssignmentContentItemQuantity 设置为 1.

Results in an AssignmentContentItem with its Quantity set to 1.

这篇关于为什么当我使用 JSON.NET 反序列化时会忽略我的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

C# 中的多播委托奇怪行为?
Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)...
2023-11-11 C#/.NET开发问题
6

参数计数与调用不匹配?
Parameter count mismatch with Invoke?(参数计数与调用不匹配?)...
2023-11-11 C#/.NET开发问题
26

如何将代表存储在列表中
How to store delegates in a List(如何将代表存储在列表中)...
2023-11-11 C#/.NET开发问题
6

代表如何工作(在后台)?
How delegates work (in the background)?(代表如何工作(在后台)?)...
2023-11-11 C#/.NET开发问题
5

没有 EndInvoke 的 C# 异步调用?
C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)...
2023-11-11 C#/.NET开发问题
2

Delegate.CreateDelegate() 和泛型:错误绑定到目标方法
Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)...
2023-11-11 C#/.NET开发问题
14