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.
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.
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.
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.
Text. Json. Serialization namespace, which contains attributes and APIs for advanced scenarios and customization specific to serialization and deserialization.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With