JavaScriptSerializer - 枚举的 JSON 序列化为字符串

JavaScriptSerializer - JSON serialization of enum as string(JavaScriptSerializer - 枚举的 JSON 序列化为字符串)
本文介绍了JavaScriptSerializer - 枚举的 JSON 序列化为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含 enum 属性的类,并且在使用 JavaScriptSerializer 序列化对象时,我的 json 结果包含枚举的整数值而不是其 字符串名称".有没有办法在我的 json 中将枚举作为 string 获取,而无需创建自定义 JavaScriptConverter?也许有一个属性可以用来装饰 enum 定义或对象属性?

I have a class that contains an enum property, and upon serializing the object using JavaScriptSerializer, my json result contains the integer value of the enumeration rather than its string "name". Is there a way to get the enum as a string in my json without having to create a custom JavaScriptConverter? Perhaps there's an attribute that I could decorate the enum definition, or object property, with?

举个例子:

enum Gender { Male, Female }

class Person
{
    int Age { get; set; }
    Gender Gender { get; set; }
}

所需的 JSON 结果:

Desired JSON result:

{ "Age": 35, "Gender": "Male" }

如果不可能的话,欢迎使用内置的 .NET 框架类寻找答案(如 Json.net).

Ideally looking for answer with built-in .NET framework classes, if not possible alternatives (like Json.net) are welcome.

推荐答案

没有可以使用的特殊属性.JavaScriptSerializerenums 序列化为它们的数值而不是它们的字符串表示.您需要使用自定义序列化将 enum 序列化为其名称而不是数值.

No there is no special attribute you can use. JavaScriptSerializer serializes enums to their numeric values and not their string representation. You would need to use custom serialization to serialize the enum as its name instead of numeric value.

如果您可以使用 JSON.Net 而不是 JavaScriptSerializer,请参阅对这个问题的回答由 OmerBakhari 提供:JSON.net 涵盖了这个用例(通过属性 [JsonConverter(typeof(StringEnumConverter))]) 和许多其他内置的 .net 序列化程序无法处理.这是一个比较序列化程序的特性和功能的链接.

If you can use JSON.Net instead of JavaScriptSerializer than see answer on this question provided by OmerBakhari: JSON.net covers this use case (via the attribute [JsonConverter(typeof(StringEnumConverter))]) and many others not handled by the built in .net serializers. Here is a link comparing features and functionalities of the serializers.

这篇关于JavaScriptSerializer - 枚举的 JSON 序列化为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)