I have a DTO class like this:
public class MyDto
{
public KeyValuePair<string, string> Identifier { get; set; }
public double Value1 { get; set; }
public string Value2 { get; set; }
}
And two instances could look like this:
var results = new List<MyDto>
{
new MyDto
{
Identifier = new KeyValuePair<string, string>("Car", "Ford"),
Value1 = 13,
Value2 = "A"
},
new MyDto
{
Identifier = new KeyValuePair<string, string>("Train", "Bombardier"),
Value1 = 14,
Value2 = "B"
},
};
When serializing the results within ASP.NET Web API (which uses Json.NET), the output looks like this:
[
{
"Identifier": {
"Key": "Car",
"Value": "Ford"
},
"Value1": 13,
"Value2": "A"
},
{
"Identifier": {
"Key": "Train",
"Value": "Bombardier"
},
"Value1": 14,
"Value2": "B"
}
]
But I'd like to have it that way:
[
{
"Car": "Ford",
"Value1": 13,
"Value2": "A"
},
{
"Train": "Bombardier",
"Value1": 14,
"Value2": "B"
}
]
How can I achieve this? Do I have to write a custom JsonConverter
and do everything by hand? Since the DTO class is located in a separate assembly not having access to Json.NET, the usage of specific Json.NET attributes is not possible.
I'm not bound to using KeyValuePair<string, string>
. I only need a data structure that allows me to have a flexible attribute name.