I need to serialize some entity classes to JSON, using Json.NET. In order to customize the names of the properties, I use the [JsonProperty]
attribute like this:
[JsonProperty("lastName")]
public string LastName { get; set; }
The problem is, I'd prefer not to have any JSON-related attributes in my entities... Is there a way to externalize the annotations somehow, so that they don't clutter my entities?
Using XmlSerializer
, it can be done easily with the XmlAttributeOverrides
class. Is there something similar for Json.NET ?
Yes, you can create a custom contract resolver and customize the JsonProperty
definition without the use of attributes. Example follows:
class Person { public string First { get; set; } }
class PersonContractResolver : DefaultContractResolver
{
protected override JsonProperty CreateProperty(
MemberInfo member,
MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
if (member.DeclaringType == typeof(Person) && member.Name == "First")
{
property.PropertyName = "FirstName";
}
return property;
}
}
class Program
{
static void Main(string[] args)
{
var result = JsonConvert.SerializeObject(
new Person { First = "John" },
new JsonSerializerSettings
{
ContractResolver = new PersonContractResolver()
});
Console.WriteLine(result);
}
}
This output of this sample program will be the following:
// {"FirstName":"John"}
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