我一直在忙着JSON一段时间,只是把它作为文本推出它并没有伤害任何人(我知道),但我想开始正确地做事.
我见过这样的JSON内容类型很多所谓的"标准":
application/json
application/x-javascript
text/javascript
text/x-javascript
text/x-json
Run Code Online (Sandbox Code Playgroud)
但哪个是正确的,还是最好的?我认为它们之间存在安全性和浏览器支持问题.
我知道有一个类似的问题,如果REST API返回JSON,那么MIME类型是什么?,但我想要一个稍微有针对性的答案.
这可能看起来有点颠倒,但我想要做的是通过其Description属性从枚举中获取枚举值.
所以,如果我有一个枚举声明如下:
enum Testing
{
[Description("David Gouge")]
Dave = 1,
[Description("Peter Gouge")]
Pete = 2,
[Description("Marie Gouge")]
Ree = 3
}
Run Code Online (Sandbox Code Playgroud)
我希望能够通过提供字符串"Peter Gouge"来获得2.
作为起点,我可以遍历枚举字段并使用正确的属性获取字段:
string descriptionToMatch = "Peter Gouge";
FieldInfo[] fields = typeof(Testing).GetFields();
foreach (FieldInfo field in fields)
{
if (field.GetCustomAttributes(typeof(DescriptionAttribute), false).Count() > 0)
{
if (((DescriptionAttribute)field.GetCustomAttributes(typeof(DescriptionAttribute), false)[0]).Description == descriptionToMatch)
{
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是那时候我仍然坚持在内心做什么.也不确定这是否是第一个出路.
使用.NET Core 中的System.Text.Json序列化器功能,如何为枚举值指定自定义值,类似于JsonPropertyName? 例如:
public enum Example {
Trick,
Treat,
[JsonPropertyName("Trick-Or-Treat")] // Error: Attribute 'JsonPropertyName' is not valid on this declaration type. It is only valid on 'property, indexer' declarations.
TrickOrTreat
}
Run Code Online (Sandbox Code Playgroud)