我可以自定义Json.NET系列化没有标注我的班?我的、自定义、Json、NET

2023-09-03 17:10:09 作者:山水不相逢

我需要使用Json.NET序列化一些实体类JSON。为了自定义属性的名称,我用的是 [JsonProperty] 属性是这样的:

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; }

现在的问题是,我想preFER不要有任何的JSON相关的属性在我的实体?有没有办法以某种方式外部化的注解,让他们不要弄乱我的实体?

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?

使用的XmlSerializer ,它可以很容易地用的 XmlAttributeOverrides 类。是否有类似的东西为Json.NET?

Using XmlSerializer, it can be done easily with the XmlAttributeOverrides class. Is there something similar for Json.NET ?

推荐答案

是的,你可以创建自定义的合同解析器,而无需使用属性自定义 JsonProperty 定义。举例如下:

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"}