Asp.Net Core3.1使用System.Text.Json替换JSON.NET
从.Net Core3.0后,微软已内置JSON解析器System.Text.Json
,不再依赖 JSON.NET
,System.Text.Json
是微软自己搞的,官网介绍说性能高于JSON.NET
,也有人做了性能比较测试,具体可参考这篇文章 Try the new System.Text.Json APIs
对于这样一个新东西,该如何使用呢,这里有两个很重要的链接,遇到问题时可翻一翻。
api文档 https://docs.microsoft.com/en-us/dotnet/api/system.text.json?view=netcore-3.1
如何使用 https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to
最后说一下最常见的问题
如何与Asp.Net Core项目集成
如果是新建.NET Core 3.0+的项目,默认已经集成,不用做什么设置。
如何用回 JSON.NET
如果用不惯System.Text.Json
,或者你已习惯JSON.NET
,那么可以在 startup 中配置。
public void ConfigureServices(IServiceCollection services)
{
...
services.AddControllers()
.AddNewtonsoftJson()
...
}
如何序列化
引用 System.Text.Json
命名空间,使用其JsonSerializer
进行序列化
var weather = new WeatherForecast
{
Date = DateTime.Now,
Summary = "this summary for test",
TemperatureC = 56
};
var jsonString = System.Text.Json.JsonSerializer.Serialize(weather);
如何不序列化某属性
在属性上加上 [JsonIgnore]
即可。
序列化时排除只读属性
配置IgnoreReadOnlyProperties
var options = new JsonSerializerOptions
{
IgnoreReadOnlyProperties = true
};
var jsonString = System.Text.Json.JsonSerializer.Serialize(weather,options);
序列化/反序列化时排除Null属性
配置IgnoreNullValues,此项默认为false。
在序列化时,如配置为true,将直接忽略输出该null值。
在反序列时,如配置为true,对null值将不再处理。
var options = new JsonSerializerOptions
{
IgnoreNullValues = true
};
var jsonString = System.Text.Json.JsonSerializer.Serialize(weather,options);
序列化时美化结果
配置WriteIndented
var options = new JsonSerializerOptions
{
WriteIndented = true
};
var jsonString = System.Text.Json.JsonSerializer.Serialize(weather,options);
自定义属性输出名称
在属性上加JsonPropertyName特性
public class WeatherForecastWithPropertyNameAttribute
{
[JsonPropertyName("Wind")]
public int WindSpeed { get; set; }
}
反序列时允许注释和逗号
逗号是指数组末尾的逗号,反序列化时遇到注释或逗号,会抛出异常,所以需配置AllowTrailingCommas,此项默认为false。
var options = new JsonSerializerOptions
{
AllowTrailingCommas = true
};
var jsonString = System.Text.Json.JsonSerializer.Serialize(weather,options);
大小写不敏感
配置 PropertyNameCaseInsensitive。此配置项只用于反序列化,默认为false,意思是默认为敏感的。
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
};
var jsonString = System.Text.Json.JsonSerializer.Serialize(weather,options);
WebApi中输出大写
Asp.Net Core WebApi中,默认输出将大写属性名称转为了小写,那如何与属性名称保持一致呢,可在startup中配置
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNamingPolicy = null;
})
PropertyNamingPolicy,此项有两个可选配置项 JsonNamingPolicy.CamelCase
,null
,当让也可以自定义一个策略。