我可以自定义Json.NET系列化没有标注我的班? [英] Can I customize Json.NET serialization without annotating my classes?

查看:130
本文介绍了我可以自定义Json.NET系列化没有标注我的班?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用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"}

这篇关于我可以自定义Json.NET系列化没有标注我的班?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆