尝试使用jSonstringEnumConverter将枚举转换为自定义字符串名称
我试图代表以下的一些用例场景。我有JSON格式化的数据。它包括一个枚举课程。他们以int类型发送了这个枚举类。我想用有意义的字符串显示此枚举值。但是我做不到。
如何显示此本登录自定义值?
编辑:我想显示“不热”值。不是Hot_Not枚举。
static void Main(string[] args) {
var jsonString = "{\"Summary\":\"40\"}";
var options = new JsonSerializerOptions {
Converters = {
new JsonStringEnumConverter()
}
};
WeatherForecastWithEnum ? weatherForecast = JsonSerializer.Deserialize < WeatherForecastWithEnum > (jsonString, options) !;
Console.WriteLine(weatherForecast.Summary);
}
public class WeatherForecastWithEnum {
public Summary ? Summary {
get;
set;
}
}
public enum Summary {
Cold = 30,
Cool = 10,
Warm = 20,
[EnumMember(Value = "Not Hot")]
Hot_Not = 40
}
I was trying represent some use-case scenario like below. I have json formatted data. And it include an enum class. They send this enum class with int type. I want to show this enum value with a meaningful string. But I couldn't make it.
How can I show this EnumMember custom value?
Edit: I want to show "Not Hot" value. Not Hot_Not enum.
static void Main(string[] args) {
var jsonString = "{\"Summary\":\"40\"}";
var options = new JsonSerializerOptions {
Converters = {
new JsonStringEnumConverter()
}
};
WeatherForecastWithEnum ? weatherForecast = JsonSerializer.Deserialize < WeatherForecastWithEnum > (jsonString, options) !;
Console.WriteLine(weatherForecast.Summary);
}
public class WeatherForecastWithEnum {
public Summary ? Summary {
get;
set;
}
}
public enum Summary {
Cold = 30,
Cool = 10,
Warm = 20,
[EnumMember(Value = "Not Hot")]
Hot_Not = 40
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
默认情况下,
system.text.json
不支持它。您可以看到相同的请求。https://github.com/dotnet/runtime/runtime/issues/issues/31081 一个称为“ macross.json.extensions”的扩展库,您可以在其中使用
jSonstringEnummemberConverter
属性,然后执行您需要的事情。您可以在 - https:// https:// github.com/macross-software/core/tree/develop/classlibraries/macross.json.extensions#enumerations
By default, it is not supported with
System.Text.Json
. You can see the request for the same.https://github.com/dotnet/runtime/issues/31081
But there is an extension library called 'Macross.Json.Extensions' where you can use
JsonStringEnumMemberConverter
attribute and then do what you need.You can see more at - https://github.com/Macross-Software/core/tree/develop/ClassLibraries/Macross.Json.Extensions#enumerations