Reputation:
I have a class with [DataContract]
and [DataMember]
attributes on it. I set the Name on the Origin
property to be custom variables
as that's what the api I'm calling provides. The problem is, that only solves the deserialization of the object. When it comes time to serialize the object, I want to serialize the Origin
property as origin
.
[DataContract]
public class Request
{
...
[DataMember(Name = "custom variables")]
public Origin Origin { get; set; }
}
For example, I want to deserialize this:
{
...
"custom variables": {
"url": "URL_HERE",
"origin": "ORIGIN_HERE"
}
}
and turn it into this upon serialization:
{
...
"origin": {
"url": "URL_HERE",
"origin": "ORIGIN_HERE"
}
}
How can I do this? Is there any way to do it without writing a custom serializer for all of the properties on the object?
Upvotes: 0
Views: 1389
Reputation: 845
As explained in the official doc:
You must decorate the property with the JsonPropertyName decorator (from the System.Text.Json.Serialization namespace).
In example:
public class WeatherForecastWithPropertyNameAttribute {
public DateTimeOffset Date { get; set; }
public int TemperatureCelsius { get; set; }
public string Summary { get; set; }
[JsonPropertyName("Wind")]
public int WindSpeed { get; set; }
}
Serialized/deserialized json:
{
"Date": "2019-08-01T00:00:00-07:00",
"TemperatureCelsius": 25,
"Summary": "Hot",
"Wind": 35
}
Upvotes: 1