无论如何要让JsonConvert.SerializeObject忽略属性上的JsonConverter属性? [英] Anyway to get JsonConvert.SerializeObject to ignore the JsonConverter attribute on a property?

查看:612
本文介绍了无论如何要让JsonConvert.SerializeObject忽略属性上的JsonConverter属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个不能更改的课程:

I have a class that I cannot change:

public enum MyEnum {
    Item1 = 0,
    Item2 = 1
}
public class foo {
    [JsonConverter(typeof(StringEnumConverter))]
    public MyEnum EnumTypes {get; set; }
}

JsonConvert.SerializeObject行的某处对对象进行序列化,并且由于JsonConverter属性的缘故,它吐出了foo.EnumTypes的枚举值的名称,而不是数字.

Somewhere down the line JsonConvert.SerializeObject serializes the object and because of the JsonConverter attribute, it spits out name of the enum value for the foo.EnumTypes rather than the number.

反正有没有办法让JsonConvert.SerializeObject忽略EnumTypes属性上的属性?

Is there anyway to get JsonConvert.SerializeObject to ignore the attribute on the EnumTypes property?

推荐答案

这是可能的,但是这个过程有点麻烦.

This is possible, but the process is a tad involved.

基本思想是创建自定义 ContractResolver 并覆盖其CreateProperty方法.像这样:

The basic idea is to create a custom ContractResolver and override its CreateProperty method. Something like so:

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

        if( member.DeclaringType == typeof( foo ) && property.PropertyType == typeof( MyEnum ) )
        {
            property.Converter = null;
        }

        return property;
    }
}

您还需要实际实例化此类并将其传递给序列化器/解串器.看起来是什么样的,完全取决于您进行序列化的方式,因此我不能保证有一个有关如何使用序列化的示例.

You'll also need to actually instantiate this class and pass it into your serializer/deserializer. What that looks like depends on exactly how you're doing the serialization, so I can't guarantee a relevant example of how to use it.

如果您仅使用静态SerializeObject方法:

If you're just using the static SerializeObject method:

JsonConvert.SerializeObject( valueToSerialize, new SerializerSettings { ContractResolver = new MyContractResolver() } );

这篇关于无论如何要让JsonConvert.SerializeObject忽略属性上的JsonConverter属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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