如何为无效值的属性使用JSON.net的默认值 [英] How to use a default value for JSON.net for properties with invalid values

查看:66
本文介绍了如何为无效值的属性使用JSON.net的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Newtonsoft JSON库反序列化来自Web服务的响应.问题在于某些字段包含无效的值.例如,一条记录上的一个字段包含应该为数字的字段的"T".我想做的是使无效字段的值为null或其他一些默认值.我所有的属性都定义为可为空,因此默认将其设置为null是可以的.

I am using the Newtonsoft JSON library to deserialize a response from a web service. The problem is that some of the fields contain values which are not valid. For example, one field on one record contained a "T" for a field that is supposed to be numeric. What I would like to do is to have values for fields that are invalid be null, or some other default value. All of my properties are defined as nullable, so it is fine if they default to null.

有没有办法做到这一点?我尝试创建自定义JsonConverters,但我希望不必为每种类型定义JsonConverter.如果可能的话,如果该属性的值无效(例如,对于数字类型为"T"),我希望对所有字段将其设置为null.

Is there a way to do this? I have tried creating custom JsonConverters, but I would prefer to not have to define a JsonConverter for each type. If possible, I would like to, for all fields, set them null if the value for that property is not valid (like a "T" for a numeric type).

我看过OnError事件处理程序,但这似乎会丢弃整个错误记录.我不想丢弃任何记录.我只想将无效属性的值设置为null.

I have looked at the OnError event handler, but that seems to discard a whole record on error. I do not want to discard any records. I would just like for the value of invalid properties to be null.

这可能吗?我一直在寻找答案,但没有找到另一个试图做到这一点的问题,但是如果我忽略了现有问题,请告诉我.

Is this possible? I have looked a lot for answers and I did not find another question that was trying to do this, but please let me know if I overlooked an existing question.

谢谢您的帮助.

推荐答案

您可以创建

You could make a JsonConverter for all nullable types that tries to deserialize the corresponding JSON value to the underlying type when non-null, and upon failure, returns null:

public class NullableTypeConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return Nullable.GetUnderlyingType(objectType) != null;
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Null)
            return null;
        var underlyingType = Nullable.GetUnderlyingType(objectType);
        if (underlyingType == null)
            throw new JsonSerializationException("Invalid type " + objectType.ToString());
        var token = JToken.Load(reader);
        try
        {
            return token.ToObject(underlyingType, serializer);
        }
        catch (Exception ex)
        {
            // Log the exception somehow
            Debug.WriteLine(ex);
            return null;
        }
    }

    public override bool CanWrite { get { return false; } }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

然后在反序列化类时使用它.

var settings = new JsonSerializerSettings { Converters = new[] { new NullableTypeConverter() } };

如果JSON本身格式错误且无法读取,则转换器仍将引发异常(从对JToken.Load()的调用).仅当JSON值在加载后无法转换为适当的类型时,它才会吞下该异常.

The converter will still throw an exception (from the call to JToken.Load()) if the JSON itself is malformed and cannot be read. It only swallows the exception if the JSON value cannot be converted to the appropriate type after being loaded.

这篇关于如何为无效值的属性使用JSON.net的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆