Newtonsoft Json.NET 反序列化仅设置 Json 字符串中的值

Newtonsoft Json.NET Deserialize Setting Only Values in Json String

Newtonsoft Json.NET 反序列化程序是否可以只分配在 Json 字符串中找到的值,即使它们是默认值并且分配了空值?

使用下面的示例,我试图找到在设置属性时添加到 _values 字典中的值。在 Json 1 中,所有值都已设置并保存到数据库中。在Json2中,设置了标识符,并将Value更新为null。反序列化后,我将在数据库中找到值,并且只想更新字典中具有值的字段。这个问题是,分配 null 实际上并没有设置值,因为它是默认值。

截至目前,我似乎能够忽略默认值,但 Value: null 被忽略了。或者我可以包含默认值,即使名称不在 Json.

中,它也会被分配为 null

我知道我可以添加...

[JsonProperty(DefaultValueHandling = DefaultValueHandling.Include)]

但在序列化时,我想忽略默认值。

解串器代码

var jsonSerializer = new JsonSerializer();
var widget = jsonSerializer.Deserialize<Widget>(jsonString);

序列化程序代码

var serializer = new JsonSerializer
{
     DefaultValueHandling = DefaultValueHandling.Ignore
};
var jsonString = serializer.Serialize(widget);

示例class

public class Widget
{
    [JsonProperty]
    public int Id { get { return Get<int>("Id"); } set { Set("Id", value); } }

    [JsonProperty]
    public string Name { get { return Get<string>("Name"); } set { Set("Name", value); } }

    [JsonProperty]
    public string Value { get { return Get<string>("Value"); } set { Set("Value", value); } }

    private Dictionary<sting, object> _values = new Dictionary<sting, object>();
    private object Get<T>(string name)
    {
        if (_values.TryGetValue(name, out value))
            return (T)value;
        else
            return default(T);
    }
    private void Set(string name, object value)
    {
        _values[name] = value;
    }
}

例子Json1

{
    "Id": 6,
    "Name": "Widget 1",
    "Value": "Blue"
}

例子Json2

{
    "Id": 6
    "Value": null
}

您可以使用 ShouldSerialize 方法,例如

bool ShouldSerializeName() {
    return _values.ContainsKey("Name");
}

bool ShouldSerializeValue() {
    return _values.ContainsKey("Value");
}

不漂亮,但应该可以。另一种选择是自定义序列化程序。