Home > Backend Development > C++ > How Can I Serialize Enums as Strings Using JavaScriptSerializer?

How Can I Serialize Enums as Strings Using JavaScriptSerializer?

Susan Sarandon
Release: 2025-01-29 09:36:11
Original
468 people have browsed it

How Can I Serialize Enums as Strings Using JavaScriptSerializer?

Use JavaScriptserializer to process enumerated string serialization

When using JavaScriptserializer serialized objects containing enumeration attributes, the JSON results often encounters problems containing an integer value instead of enumerated string representation.

Consider a sample class containing enumeration attributes:

<code class="language-csharp">public class Person
{
    public int Age { get; set; }
    public Gender Gender { get; set; }
}</code>
Copy after login
The expected json result:

Question:
<code class="language-json">{ 
    "Age": 35, 
    "Gender": "Male" 
}</code>
Copy after login

Using JavaScriptserializer, the gender attribute will be serialized to an integer value, such as "gender": 0 instead of "gender": "male".

Solution:

Use newtonsoft.json newtonsoft.json provides a solution to use the

attribute:

The global configuration converter [JsonConverter]

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

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

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

Add

attributes to the lift itself, and serialize/counter -serialization of all instances into string.
  • JSONSERIALIZER: Add the converter to serializer so that all enumerations are processed during the serialization process. [JsonConverter] JSONCONVERR class:
  • Serialize the transformer to control the enumeration of the specific object.
  • Other configuration:
  • The constructor allows control of controlling and values.

The above is the detailed content of How Can I Serialize Enums as Strings Using JavaScriptSerializer?. 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