Mapping multiple property names to the same field in Newtonsoft.JSON

半世苍凉 提交于 2019-12-11 02:12:34

问题


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.

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

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

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

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.

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


回答1:


You could use a custom ContractResolver in this answer:

Json.NET deserialize or serialize json string and map properties to different property names defined at runtime

Or

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

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



来源:https://stackoverflow.com/questions/49253411/mapping-multiple-property-names-to-the-same-field-in-newtonsoft-json

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