C# 用于在JSON.NET中反序列化十进制值的自定义规则

C# 用于在JSON.NET中反序列化十进制值的自定义规则,c#,json,json.net,C#,Json,Json.net,当使用JsonConvert.DeserializeObject将JSON数据转换为自定义类时,每当属性的null值应为decimal时,我就会遇到问题 我想实现一个自定义规则,它只在我想要的时候使用——不需要全局设置。在这种特殊情况下,只要属性是十进制类型,我就希望null值变为0 如何实现这一点?您可以在反序列化的类型中使用注释,或者在反序列化时指定自定义转换器/设置(而不是全局)。我认为,处理某些十进制属性的唯一好方法是使用注释 string json = @"{""val"": null

当使用
JsonConvert.DeserializeObject
JSON
数据转换为自定义类时,每当属性的
null
值应为
decimal
时,我就会遇到问题

我想实现一个自定义规则,它只在我想要的时候使用——不需要全局设置。在这种特殊情况下,只要属性是十进制类型,我就希望
null
值变为
0


如何实现这一点?

您可以在反序列化的类型中使用注释,或者在反序列化时指定自定义转换器/设置(而不是全局)。我认为,处理某些
十进制
属性的唯一好方法是使用注释

string json = @"{""val"": null}";

public class NoAnnotation {
    public decimal val {get; set;}
}

public class WithAnnotation {
    [JsonConverter(typeof(CustomDecimalNullConverter))]
    public decimal val {get; set;}
}

void Main()
{   
    // Converting a type that specifies the converter
    // with attributes works without additional setup
    JsonConvert.DeserializeObject(json, typeof(WithAnnotation));

    // Converting a POCO doesn't work without some sort of setup,
    // this would throw
    // JsonConvert.DeserializeObject(json, typeof(NoAnnotation));

    // You can specify which extra converters
    // to use for this specific operation.
    // Here, the converter will be used
    // for all decimal properties
    JsonConvert.DeserializeObject(json, typeof(NoAnnotation),
       new CustomDecimalNullConverter());

    // You can also create custom serializer settings.
    // This is a good idea if you need to serialize/deserialize multiple places in your application,
    // now you only have one place to configure additional converters
    var settings = new JsonSerializerSettings();
    settings.Converters.Add(new CustomDecimalNullConverter());
    JsonConvert.DeserializeObject(json, typeof(NoAnnotation), settings);
}

// For completeness: A stupid example converter
class CustomDecimalNullConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(decimal);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Null)
        {
            return 0m;
        }
        else
        {
            return Convert.ToDecimal(reader.Value);
        }
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteValue((decimal)value);
    }
}

[JsonConverter(typeof(NullToDefaultConverter))]
我认为应该可以。关闭的答案是否足以将其标记为重复,还是需要更具体的东西?该示例非常完美。我对你的评论投了赞成票,并接受@gnud的回复作为答案。非常感谢。谢谢你的详细回答。很好用!