Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple JsonProperty Name assigned to single property

I have two format of JSON which I want to Deserialize to one class. I know we can't apply two [JsonProperty] attribute to one property.

Can you please suggest me a way to achieve this?

string json1 = @"     {         'field1': '123456789012345',         'specifications': {             'name1': 'HFE'         }     }";  string json2 = @"     {         'field1': '123456789012345',         'specifications': {             'name2': 'HFE'         }     }";  public class Specifications {     [JsonProperty("name1")]     public string CodeModel { get; set; } }  public class ClassToDeserialize {     [JsonProperty("field1")]     public string Vin { get; set; }      [JsonProperty("specification")]     public Specifications Specifications { get; set; }         } 

I want name1 and name2 both to be deserialize to name1 property of specification class.

like image 776
Vivek Tiwari Avatar asked May 01 '17 03:05

Vivek Tiwari


People also ask

How to set JsonProperty name in c#?

To set the name of individual properties, use the [JsonPropertyName] attribute. The property name set by this attribute: Applies in both directions, for serialization and deserialization.

What is JsonProperty annotation C#?

JsonPropertyAttribute indicates that a property should be serialized when member serialization is set to opt-in. It includes non-public properties in serialization and deserialization. It can be used to customize type name, reference, null, and default value handling for the property value.

What is JSON property name?

The Jackson Annotation @JsonProperty is used on a property or method during serialization or deserialization of JSON. It takes an optional 'name' parameter which is useful in case the property name is different than 'key' name in JSON.

What is System Text JSON?

Text. Json. Serialization namespace, which contains attributes and APIs for advanced scenarios and customization specific to serialization and deserialization.


1 Answers

A simple solution which does not require a converter: just add a second, private property to your class, mark it with [JsonProperty("name2")], and have it set the first property:

public class Specifications {     [JsonProperty("name1")]     public string CodeModel { get; set; }      [JsonProperty("name2")]     private string CodeModel2 { set { CodeModel = value; } } } 

Fiddle: https://dotnetfiddle.net/z3KJj5

like image 138
Brian Rogers Avatar answered Sep 24 '22 14:09

Brian Rogers