将多个属性名称映射到Newtonsoft.JSON中的相同字段 [英] Mapping multiple property names to the same field in Newtonsoft.JSON

查看:506
本文介绍了将多个属性名称映射到Newtonsoft.JSON中的相同字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在分布式系统中有两个组件,它们发送使用Newtonsoft.JSON(JSON.Net)进行序列化/反序列化的消息.

I have two components in a distributed system, which send messages which are serialized/deserialized using Newtonsoft.JSON (JSON.Net).

消息属性当前以挪威语发送,我希望将代码库翻译成英语.由于存在一些更改,即某些消息将以挪威语发送,并由已升级为英语版本的组件处理,因此它必须能够同时支持这两种消息.

The message properties are currently sent in Norwegian, and I am looking to translate the codebase to English. Since there is a change that some messages would have been sent in Norwegian, and handled by a component which has been upgraded to the English version, it needs to be able to support both.

在反序列化时,我希望将"Norwegian"属性名称和英语都映射到同一属性.例如:

I would like that on deserialization, both the 'Norwegian' property name as well as English would map to the same property. For example:

例如,使用英语的名称"或挪威语的"navn".

For example, take 'name' in English or 'navn' in Norwegian.

public class Message
{
     [JsonProperty("Navn")]
     public string Name { get; set;}
}

上述问题是仅从Navn => Name映射.我想将NavnName都映射到Name.

The problem with the above is that it would map only from Navn => Name. I would like it to map both Navn and Name to Name.

是否可以在Newtonsoft.JSON中使用它,而无需进行大量自定义编码?

Is this available in Newtonsoft.JSON, without much custom coding?

推荐答案

您可以在此答案中使用自定义的ContractResolver:

You could use a custom ContractResolver in this answer:

Json.NET反序列化或序列化json字符串,并将属性映射到运行时定义的不同属性名称

使用[JsonProperty(")]查找属性名称的不同变体,并返回如下属性之一:

Use [JsonProperty("")] to look for different variations of the property name and return with one of the properties like this:

public class Message
{
   private string _name;

   [JsonProperty("Navn" )]
   public string NorwegianName { get; set; }

   [JsonProperty("Name")]
   public string Name { 
      get { return _name ?? NorwegianName; } 
      set { _name = value; } }
}

这将返回带有JSON属性名称的名称:NavnName.

This will return the name with JSON property name: Navn or Name.

这篇关于将多个属性名称映射到Newtonsoft.JSON中的相同字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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