Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anyway to get JsonConvert.SerializeObject to ignore the JsonConverter attribute on a property?

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; }
}

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.

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

like image 367
AngryHacker Avatar asked Aug 11 '17 21:08

AngryHacker


People also ask

How do I ignore JSON property?

To ignore individual properties, use the [JsonIgnore] attribute. You can specify conditional exclusion by setting the [JsonIgnore] attribute's Condition property. The JsonIgnoreCondition enum provides the following options: Always - The property is always ignored.

How does Jsonconvert SerializeObject work?

SerializeObject Method. Serializes the specified object to a JSON string. Serializes the specified object to a JSON string using formatting.

Which of the following attribute should be used to indicate the property must not be serialized while using .JSON serializer?

Apply a [JsonIgnore] attribute to the property that you do not want to be serialized.

What does Jsonconvert SerializeObject return?

Return ValueA JSON string representation of the object.


1 Answers

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

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.

If you're just using the static SerializeObject method:

JsonConvert.SerializeObject( valueToSerialize, new SerializerSettings { ContractResolver = new MyContractResolver() } );
like image 76
Kyle Avatar answered Nov 03 '22 01:11

Kyle