当前位置:网站首页>.net serialize enumeration as string
.net serialize enumeration as string
2022-07-29 02:51:00 【Phil Arist】
By default , Enumeration is in its integer form JSON serialize , This usually leads to lack of interoperability with consumer applications , Because they need to know the actual meaning of these numbers in advance . therefore , We want them to be serialized as strings in some cases . This article will explain various ways to achieve this goal .
1 The default behavior of enumeration serialization
To demonstrate , Let's create a simple Model:
public class Circle
{
public double Radius { get; set; }
public Color BgColor { get; set; }
}
public enum Color
{
White, LightGray, Black
} We use it System.Text.Json Medium Serialize Method serializes a Circle object :
using System.Text.Json;
var json = JsonSerializer.Serialize(new Circle
{
Radius = 10.1,
BgColor = Color.Black
});
Console.WriteLine(json);Let's take a look at this Model Serialize to Json String after :
{ "Radius": 10.1, "BgColor": 2 } As you can see , Enumerate the values of attributes (Color.Black) Serialized as JSON The string is followed by an integer (2).
As a result of serialization JSON The consumer , Without documentation , It is impossible to know the business meaning represented by this integer .
therefore , The problem is coming. . How to convert the enumeration attribute sequence into a more intuitive string form ? namely , How to serialize the object in the above example into :
{ "Radius": 10.1, "BgColor": "Black" } To serialize an enumeration into a string ,Dotnet Standard library System.Text.Json and Newtonsoft Libraries provide a converter for this , Respectively JsonStringEnumConverter and StringEnumConverter. Let's see their usage .
2 Based on annotation
Dotnet Standard library and Newtonsoft Libraries provide a converter feature JsonConverterAttribute, We can use it to selectively mark enumerated properties or types to be serialized as strings .
Label enumeration properties
We can use JsonConverterAttribute Feature to label BgColor attribute , And use JsonStringEnumConverter converter , as follows :
using System.Text.Json.Serialization;
public class Circle
{
public double Radius { get; set; }
[JsonConverter(typeof(JsonStringEnumConverter))]
public Color BgColor { get; set; }
}At this time, the result of serialization is :
{ "Radius": 10.1, "BgColor": "Black" }Newtonsoft Libraries are similar , hold JsonStringEnumConverter Replace with StringEnumConverter that will do , This article will not repeat the list .
Annotation enumeration type
JsonConverterAttribute Features can also be applied to custom types , Apply it to Color On enum type :
using System.Text.Json.Serialization;
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum Color
{
White, LightGray, Black
} such , be-all Color Enumerations are serialized as strings .
3 Option based approach
In some inconvenient modifications Model Or enumeration type definition ( Such as calling a third party SDK), You can't serialize enumerations into strings using annotations .Dotnet Standard library and Newtonsoft The library also provides serialization methods with conversion option parameters , Allow us to use in-line (Inline) How to achieve this goal .
Dotnet Examples of standard libraries are as follows :
public static string SerializeWithStringEnum(object obj)
{
var options = new JsonSerializerOptions();
options.Converters.Add(new JsonStringEnumConverter());
return JsonSerializer.Serialize(obj, options);
}and Newtonsoft The library is slightly different :
public static string SerializeWithStringEnum(object obj)
{
var converter = new StringEnumConverter();
return JsonConvert.SerializeObject(obj, converter);
}4 Global registration
The method based on feature annotation allows us to flexibly operate the serialization of enumeration in a controllable way . The option based approach allows us to process the serialization of objects on demand in a specific environment . however , Is there any way to serialize all enumerations into strings by default ? The answer is yes .
For console applications or Dotnet The class library is simple , Directly encapsulate a general serialization method . Here we are mainly concerned about how to ASP.NET Core Register global serialization rules in the application .
stay ASP.NET Core Web API Application , Need to be in DI Register enumeration converters in the pipeline , as follows :
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
});
var app = builder.Build();
app.MapControllers();
app.Run(); stay ASP.NET Core Minimal API in , Also needed in the DI Register enumeration converters in the pipeline , But it uses Configure The way :
var builder = WebApplication.CreateBuilder(args);
builder.Services.Configure<JsonOptions>(options =>
{
options.SerializerOptions.Converters.Add(new JsonStringEnumConverter());
});
var app = builder.Build();
app.MapGet("/", () => new Circle
{
Radius = 10.1,
BgColor = Color.Black
});
app.Run();As mentioned above , We can set the application to serialize enumerations into strings by default through global registration , This will keep Model It's clean , There is no need to specify explicit options when serializing .
5 Serialization of flag enumeration
Mark the enumeration (bit-mask enumeration ) The default serialized output of is also an integer , Instead of using signs (Flag) A combination of . for example :
using System.Text.Json;
var colors = Color.LightGray | Color.Black;
var json = JsonSerializer.Serialize(new { Colors = colors });
Console.WriteLine(json);
[Flags]
public enum Color
{
White = 0,
LightGray = 1,
Black = 2
}The serialization result is :
{ "Colors": 3 }What we want to output is a combination of enumerations , The result is a number , It is difficult for consumers to understand its true meaning , We want it serialized as a combination of files . Using the previous enumeration string converter can solve this problem , Take the option based approach as an example , The sample code is as follows :
using System.Text.Json;
using System.Text.Json.Serialization;
var options = new JsonSerializerOptions();
options.Converters.Add(new JsonStringEnumConverter());
var colors = Color.LightGray | Color.Black;
var json = JsonSerializer.Serialize(new { Colors = colors }, options);
Console.WriteLine(json);{ "Colors": "LightGray, Black" }In this way, we get the text combination serialization result we want .
6 Custom enumeration string
When serializing enumerations into strings , We may want to make some fine adjustments . for example , Convert to camelCase Or other more meaningful text forms .
Serialize to camelCase form
JsonStringEnumConverter There is an overloaded constructor that receives naming policies , Pass it in JsonNamingPolicy.CamelCase Parameter, the enumeration sequence can be camelCase Text form , for example :
var options = new JsonSerializerOptions();
options.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase));
var json = JsonSerializer.Serialize(new Circle
{
Radius = 10.1,
BgColor = Color.LightGray
});
Console.WriteLine(json);The serialization result is :
{ "Radius": 10.1, "BgColor": "lightGray" }Serialize as custom text
Because of the variable naming rules in language , Enumeration members do not always convey meaningful text when serialized in a conventional way . To solve this problem , We can use EnumMemberAttribute characteristic , It was introduced specifically for this purpose . Let's define a new enumeration :
public enum ColorScheme
{
[EnumMember(Value = " white / blue ")]
WhiteBlue,
[EnumMember(Value = " red / black ")]
RedBlack,
} We define a ColorScheme enumeration , Mark on its members EnumMember characteristic , To provide more meaningful textual expression .
I'm sorry ,Donet Standard library System.Text.Json Native does not support this kind of customized text serialization . but Newtonsoft Libraries are supported , The sample code is as follows :
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Runtime.Serialization;
var converter = new StringEnumConverter();
var json = JsonConvert.SerializeObject(new TShirt
{
Name = " Men's shirts - Casual style ",
ColorScheme = ColorScheme.WhiteBlue
}, converter);
Console.WriteLine(json);
public class TShirt
{
public string? Name { get; set; }
public ColorScheme ColorScheme { get; set; }
}Output the result after serialization :
{ "Name": " Men's shirts - Casual style ", "ColorScheme": " white / blue " }After serialization , We can see that it outputs the text we want .
notes : although Donet The standard library native does not support serializing enumerations into custom text , But it can still be achieved by customizing the converter .
7 summary
Enumeration defaults to its integer form JSON Serialized , This requires consumers to understand the actual meaning of these figures in advance , It also brings some difficulties to the understanding of the code . therefore Dotnet Basic libraries and popular Newtonsoft Libraries provide many ways to serialize enumerations into strings . According to the demand , You can choose to use the method of property-based annotation described in this article 、 Based on option parameters and global methods .
in addition , In addition, enumerations can be serialized into member namers , You can also customize the output of text , If the output is camelCase Text form and customized output text content .
边栏推荐
- Which is a good automatic account distribution system?
- Etcd implementation of large-scale service governance application practice
- etcd实现大规模服务治理应用实战
- FTP protocol details
- 九宫格心形拼图小程序源码/带流量主微信小程序源码
- C语言:空心正方形图案
- Some records during the development of ros2/ros1
- New UI Sifang aggregate payment system source code / new usdt withdrawal / latest update security upgrade to fix XSS vulnerability patch vulnerability
- sqlilabs less-32~less-33
- PHP幸运抽奖系统带后台源码
猜你喜欢

第八天笔记

FFmpeg+SDL+QT实现简单是视频播放器

STM32F103 learn the steps and template fool tutorial of 1-keil5 project establishment

Flink kernel source code (VII) Flink SQL submission process

FTP协议详解

PHP lucky draw system with background source code

New UI Sifang aggregate payment system source code / new usdt withdrawal / latest update security upgrade to fix XSS vulnerability patch vulnerability

Day 5 experiment

Asemi rectifier bridge s25vb100, s25vb100 parameters, s25vb100 application

用于校园流浪猫信息记录和分享的小程序源码/微信云开发中大猫谱小程序源码
随机推荐
C language: Little Lele and Euclid
双for循环
[opencv] use OpenCV to call mobile camera
11. Writing rules - pseudo target
New conch movie theme template m3.1 fully decrypted version multifunctional apple cmsv10 background adaptive theme open source fully decrypted version
Time for white horses to pass the gap
混淆矩阵学习笔记
Double for loop
多线程实现多用例文件并发读取执行+Selenium Grid4实现测试框架分布式部署
This blogger has a comprehensive classification of QT. If you are free, go to study and summarize it and record it.
解析机器人与人类情感共鸣的主观意识
STP protocol (spanning tree protocol)
Trample --- discretization + tree array + difference
第七天笔记
nacos名字的由来
Source code and display of 18 classic programs in C language vs2019
owt-server源码剖析(四)--video模块分析之Mixer Out
Implementation principle of golang synergy
解析Steam教育中的项目式学习创造力
12. Writing rules - static mode