Home > Backend Development > C++ > How to Serialize Enums as Strings Using JavaScriptSerializer and Json.NET?

How to Serialize Enums as Strings Using JavaScriptSerializer and Json.NET?

Linda Hamilton
Release: 2025-01-29 09:26:10
Original
119 people have browsed it

How to Serialize Enums as Strings Using JavaScriptSerializer and Json.NET?

javascriptserializer and json.net enumeration serialized into string

When using the JavaScriptserializer serialized objects that contain enumeration attributes, the default behavior is an integer value output an enumerated value instead of its string representation. This article discusses the method of customizing this behavior and obtaining enumeration string in the JSON output. There is no need to use custom JavaScriptConverters.

Solution using json.net

JSON.NET provides more convenient solutions through its JSONCONVERTER attributes and built -in StringenumConverter types. By applying the attribute to the related enumeration attributes:

... You can specify the enumeration to serialize as a string. For more information about StringenumConverter, see its documents.

<code class="language-csharp">using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

[JsonConverter(typeof(StringEnumConverter))]
public Gender Gender { get; set; }</code>
Copy after login
Other options

There are other methods that can configure this converter global:

Epolid definition:

Add the attribute to the lift itself to ensure that all enumeration instances serialize into string.

    JSONSERIALIZER:
  • Including converters in JSONSERIALIZER:
  • This method applies the converter to all the enumeration encountered in the process of serialization.
  • jsonconveter:
Another method is to use the JSONCONVERT class:
<code class="language-csharp">serializer.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());</code>
Copy after login

    Further customized
  • StringenumConverter allows other customs, such as controlling the lowercase of the enumeration string and whether to accept the value. This can be implemented through StringenumConVerter (Namingstrategy, Boolean).

The above is the detailed content of How to Serialize Enums as Strings Using JavaScriptSerializer and Json.NET?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template