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"
}
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?).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With