Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable/disable usage of specified [JsonProperty] name

Tags:

c#

json.net

Is there a way how to programmatically enable/disable usage of property name specified by [JsonProperty]?

When I serialize:

public class Dto
{
    [JsonProperty("l")]
    public string LooooooooooooongName { get; set; }
}

I would like to be able to see an output "in debug":

{
    "LooooooooooooongName":"Data"
}

And "in release":

{
    "l":"Data"
}
like image 565
Vojtech B Avatar asked Sep 15 '15 16:09

Vojtech B


2 Answers

Just create a resolver to handle the job.

public class NoJsonPropertyNameContractResolver : DefaultContractResolver
{

    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {

        JsonProperty property = base.CreateProperty(member, memberSerialization);
        property.PropertyName = property.UnderlyingName;
        return property;
    }
}

and somewhere in your startup code

#if DEBUG
JsonConvert.DefaultSettings = () => new JsonSerializerSettings()
        {
                ContractResolver = new NoJsonPropertyNameContractResolver()
        };
#endif

You now have inconsistent behaviour between your Debug and Release build (but why?).

like image 139
tia Avatar answered Sep 19 '22 20:09

tia


You can try to use C# preprocessor directives:

public class Dto
{
#if !DEBUG
    [JsonProperty("l")]
#endif    
    public string LooooooooooooongName { get; set; }
}

EDIT

Ок, maybe this is not very convenient if you must do it around the whole application. Another more convenient approach could be to implement custom ContractResolver and place this preprocessor directive only in one place.

public class CustomContractResolver : DefaultContractResolver
{
    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        var prop = base.CreateProperty(member, memberSerialization);

#if DEBUG
        if(prop != null)
        {
            // If in debug mode -> return PropertyName value to the initial member name. 
            prop.PropertyName = member.Name;
        }
#endif

        return prop;
    }
}

And the usage:

var jsonString = JsonConvert.SerializeObject(someObj, new JsonSerializerSettings
{
    ContractResolver = new CustomContractResolver(),
});

Note: you can implement wrapper around JsonConverter or use default json serializer settings, so you wont need to specify the contract resolver every time.

like image 34
Viktor Bahtev Avatar answered Sep 19 '22 20:09

Viktor Bahtev