Reputation: 24789
I have a custom class, which basically boils down to this:
public class MyValue
{
public MyValue(int v)
{
Value = v;
}
public int Value {get;}
}
I use this class as a property on various classes. When my API returns a class (which has a MyValue
property), the json returned looks like:
"propertyOfTypeMyValue": {
"value": 4
}
I don't want this. What I'd like is that the json returned looks like this:
"propertyOfTypeMyValue": 4
Is this possible? If so, how?
Upvotes: 1
Views: 72
Reputation: 129677
Yes, it is possible to get the output you want by creating a custom JsonConverter
for your MyValue
class like this:
public class MyValueConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(MyValue);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
if (reader.TokenType == JsonToken.Integer)
return new MyValue(Convert.ToInt32(reader.Value));
throw new JsonException("Unexpected token type: " + reader.TokenType);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(((MyValue)value).Value);
}
}
To use the converter, mark the MyValue
class with a [JsonConverter]
attribute:
[JsonConverter(typeof(MyValueConverter))]
public class MyValue
{
public MyValue(int v)
{
Value = v;
}
public int Value { get; private set; }
}
Here is a working demo: https://dotnetfiddle.net/A4eU87
Upvotes: 1