序列化json时如何忽略JsonProperty(PropertyName ="someName")? [英] How to ignore JsonProperty(PropertyName = "someName") when serializing json?

查看:1092
本文介绍了序列化json时如何忽略JsonProperty(PropertyName ="someName")?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些使用ASP.Net MVC的C#代码,该代码利用Json.Net来序列化一些DTO.为了减少有效负载,我利用了[JsonProperty(PropertyName ="shortName")]属性在序列化过程中使用较短的属性名称.

I have some C# code using ASP.Net MVC, which is making use of Json.Net to serialize some DTOs. In order to reduce payload, I have made use of the [JsonProperty(PropertyName = "shortName")] attribute to use shorter property names during serialization.

当客户端是另一个.Net应用程序或服务时,这非常有用,因为反序列化使用更长的更友好的名称将对象层次结构重新组合在一起,同时保持较低的实际传输有效负载.

This works great when the client is another .Net app or service, as the deserialization puts the object hierarchy back together, using the longer more friendly names, while keeping actual transfer payload low.

当客户端通过浏览器使用javascript/ajax时,该问题就起作用了.它发出请求,并获取json ...,但该json使用的是简短的不太友好的名称.

The problem comes into play when the client is javascript/ajax through a browser. It makes the request, and gets the json ... but that json is using the shortened less-friendly names.

如何使json.net序列化引擎忽略以编程方式忽略[JsonProperty(PropertyName ="shortName")]属性?理想情况下,我的MVC服务将坐在那里运行,并且通常使用缩短的属性名称进行序列化.当我的代码检测到特定参数时,我想使用更长的名称来序列化数据,而忽略[JsonProperty()]属性.

How can I make the json.net serialization engine ignore the [JsonProperty(PropertyName = "shortName")] attribute programmatically? Ideally, my MVC service is going to sit there running and normally serialize using the shortened property names. When my code detects a particular parameter, I'd like to get the data serialized using the longer names and ignore the [JsonProperty()] attribute.

有什么建议吗?

谢谢

凯文

推荐答案

使用自定义合同解析器可以轻松完成此操作.这是您需要的所有代码:

This can be done pretty easily using a custom contract resolver. Here's all the code you would need:

class LongNameContractResolver : DefaultContractResolver
{
    protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
    {
        // Let the base class create all the JsonProperties 
        // using the short names
        IList<JsonProperty> list = base.CreateProperties(type, memberSerialization);

        // Now inspect each property and replace the 
        // short name with the real property name
        foreach (JsonProperty prop in list)
        {
            prop.PropertyName = prop.UnderlyingName;
        }

        return list;
    }
}

以下是使用解析器的快速演示:

Here's a quick demo using the resolver:

class Program
{
    static void Main(string[] args)
    {
        Foo foo = new Foo
        {
            CustomerName = "Bubba Gump Shrimp Company",
            CustomerNumber = "BG60938"
        };

        Console.WriteLine("--- Using JsonProperty names ---");
        Console.WriteLine(Serialize(foo, false));
        Console.WriteLine();
        Console.WriteLine("--- Ignoring JsonProperty names ---");
        Console.WriteLine(Serialize(foo, true));
    }

    static string Serialize(object obj, bool useLongNames)
    {
        JsonSerializerSettings settings = new JsonSerializerSettings();
        settings.Formatting = Formatting.Indented;
        if (useLongNames)
        {
            settings.ContractResolver = new LongNameContractResolver();
        }

        return JsonConvert.SerializeObject(obj, settings);
    }
}

class Foo
{
    [JsonProperty("cust-num")]
    public string CustomerNumber { get; set; }
    [JsonProperty("cust-name")]
    public string CustomerName { get; set; }
}

输出:

--- Using JsonProperty names ---
{
  "cust-num": "BG60938",
  "cust-name": "Bubba Gump Shrimp Company"
}

--- Ignoring JsonProperty names ---
{
  "CustomerNumber": "BG60938",
  "CustomerName": "Bubba Gump Shrimp Company"
}

这篇关于序列化json时如何忽略JsonProperty(PropertyName ="someName")?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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