gpt4 book ai didi

c# - MediaTypeFormatter 序列化 web api 中的枚举字符串值

转载 作者:IT王子 更新时间:2023-10-29 04:51:49 25 4
gpt4 key购买 nike

考虑这段代码:

public Gender Get()
{
return Gender.Female;
}
public enum Gender
{
Male,
Female
}

此代码是一个返回 Gender 枚举的 Web API Controller 。当我们使用 XmlTypeFormatter 并调用该方法时,它返回 MaleFemale。但是当我们使用 JsonTypeFormatter 时,我们得到的是 enum 的值,比如 1。

为什么会这样?!以及如何从 JsonTypeFormatter 获取 FemaleMale

最佳答案

在您的应用程序中开始:

using Newtonsoft.Json;

protected void Application_Start()
{
SerializeSettings(GlobalConfiguration.Configuration);

}

void SerializeSettings(HttpConfiguration config)
{
JsonSerializerSettings jsonSetting = new JsonSerializerSettings();
jsonSetting.Converters.Add(new Converters.StringEnumConverter());
config.Formatters.JsonFormatter.SerializerSettings = jsonSetting;
}

关于c# - MediaTypeFormatter 序列化 web api 中的枚举字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20242035/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com