Map class with json.net

1

Is there any way to map the properties of a class without using annotation JsonProperty of Json.NET

The following structure shows two classes that inherit from the Bar class. However, the json name of the parent property (Bar) should be different in the serialization of the two child classes.

public class Bar
{
    [JsonProperty("property_1")]
    public string Property1 {get; set;}
}

public class Foo : Bar
{
    [JsonProperty("property_2")]
    public string Property2 {get;set;}
}

public class FooBar : Bar
{
    [JsonProperty("property_3")]
    public string Property3 {get;set;}
}

In addition, I'd like to avoid placing annotations on the application's domain entities by mapping to json in a separate project.

    
asked by anonymous 05.05.2016 / 20:14

1 answer

1

Vinicius, alternatively, you can use the Attributes [DataContract] and [DataMember] instead of [JsonObject] and [JsonProperty] respectively.

But when you do this, you will have to put [DataMember] on all properties that you want to serialize, since omitting [DataMember] will be the same as adding [JsonIgnore] .

This approach can be very useful if you want to expose your objects with WebAPI or WCF , including [DataMember] has the EmitDefaultValue attribute, if set to false, it will not serialize properties while are set to default .

But if you know how to declare the property name in a way that does not use Attributes , unfortunately you will have to write your own JsonConverter , so it may not be viable.

If you prefer, you can add the attributes to other classes, to do so use the [MetadataType] Attributes, this approach is especially useful to keep attributes in automatically generated classes, so let's take as base the following class: / p>

public partial class MyClass
{
    public string Property1 {get; set;}
    public string Property2 {get; set;}
    public string Property3 {get; set;}
}

then we would have to do the following in a separate file:

[MetadataType(typeof(MyMetaData))]
public partial class MyClass
{

}

public class MyMetaData
{
    [DataMember(Name = "property_1")]
    public string Property1 {get; set;}

    [DataMember(Name = "property_2")]
    public string Property2 {get; set;}

    [DataMember(Name = "property_3")]
    public string Property3 {get; set;}
}

Although I believe the answer above did not solve your problem, I hope I gave you a north.

    
05.05.2016 / 20:40