问题
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 ?
回答1:
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"}
来源:https://stackoverflow.com/questions/11880677/can-i-customize-json-net-serialization-without-annotating-my-classes