Can I customize Json.NET serialization without annotating my classes?

浪尽此生 提交于 2019-12-09 02:56:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!