【问题标题】:How to format a custom type in the json result?如何在 json 结果中格式化自定义类型?
【发布时间】:2020-04-29 14:36:55
【问题描述】:

我有一个自定义类,基本上可以归结为:

public class MyValue
{
    public MyValue(int v)
    {
        Value = v;
    }

    public int Value {get;}
}

我将这个类用作各种类的属性。当我的 API 返回一个类(具有 MyValue 属性)时,返回的 json 如下所示:

"propertyOfTypeMyValue": {
    "value": 4
}

我不想要这个。我想要的是返回的 json 看起来像这样:

"propertyOfTypeMyValue": 4

这可能吗?如果有,怎么做?

【问题讨论】:

标签: c# json asp.net-web-api asp.net-web-api2


【解决方案1】:

是的,可以通过为您的 MyValue 类创建自定义 JsonConverter 来获得所需的输出,如下所示:

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);
    }
}

要使用转换器,请使用[JsonConverter] 属性标记MyValue 类:

[JsonConverter(typeof(MyValueConverter))]
public class MyValue
{
    public MyValue(int v)
    {
        Value = v;
    }

    public int Value { get; private set; }
}

这是一个工作演示:https://dotnetfiddle.net/A4eU87

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-24
    • 2021-10-15
    • 1970-01-01
    • 2011-01-27
    • 1970-01-01
    • 2019-04-19
    相关资源
    最近更新 更多