捕获异常并为JSONProperty设置值

时间:2014-06-24 09:12:44

标签: c# json.net

我想捕获JSON.NET的CreateProperty方法中的异常,并用该属性中出现的异常替换属性的类型和消息。

这是我到目前为止所实现的目标。

class CustomResolver : DefaultContractResolver
{
    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        JsonProperty property = base.CreateProperty(member, memberSerialization);

        property.ShouldSerialize = instance =>
        {
            var prop = (PropertyInfo)member;
            try
            {
                if (prop.CanRead)
                {
                    prop.GetValue(instance, null);
                }
            }
            catch(Exception exception)
            {
                property.PropertyType = typeof(string);
                property.DefaultValue = exception.Message;
                return true;
            }
            return true;
        };

        return property;
    }
}

我有一堂课。

class MyClass{
    public int Id {get; set;}
    public decimal Amount
    {
            get { throw new Exception("Test Exception"); }
    }
}

现在,我正在尝试序列化该对象:

var obj = new MyClass();

var convertedString = JsonConvert.SerializeObject(obj, Formatting.Indented,
                new JsonSerializerSettings
                {
                    ReferenceLoopHandling =
                        ReferenceLoopHandling.Ignore,
                    Converters = new List<JsonConverter>
                    {
                        new IsoDateTimeConverter
                        {
                            DateTimeFormat =
                                "yyyy-MM-dd hh:mm:ss"
                        }
                    },
                    ContractResolver = new CustomResolver()
                });

我想要实现的目标是:

{
    "Id" : 0,
    "Amount" : "Test Exception"
}

但这似乎并没有奏效。任何人都可以帮我解决这个问题。

由于

0 个答案:

没有答案
相关问题