cra*_*aig 5 c# asp.net-mvc json.net .net-core system.text.json
我将.Net Core的版本从预览2升级到了预览6,这打破了两件事。最重要的是,我不能再使用newtonsoft JSON。
ConfigureServices中的AddNewtonsoftJson似乎什么也不做,新的Json序列化器似乎仅对属性起作用,而对字段不起作用。它没有看到JSONIgnoreAttribute。
在ConfigureServices中(在Startup中),我有一行
services.AddMvc(x => x.EnableEndpointRouting = false).AddNewtonsoftJson();
似乎没有做应做的事情。在我的应用程序中,仅属性被序列化,而不是字段,并且[JSONIgnore]属性不执行任何操作。
我可以通过推广所有需要成为属性的公共领域来解决缺少的领域,但是我必须能够忽略一些领域。
还有其他人吗?如何获得新的JSON序列化程序以忽略某些属性并序列化公共字段,或者返回Newtonsoft?
System.Text.Json 有一个JsonIgnore属性,请参阅如何使用 System.Text.Json 忽略属性。
为了使其工作,您需要删除对 Newtonsoft.Json 的依赖并将相关文件中的命名空间更改为System.Text.Json.Serialization;
Sytem.Text.Json 可以包含字段,但只能包含公共字段。
using System.Text.Json;
using System.Text.Json.Serialization;
var json = JsonSerializer.Serialize(new O(), new JsonSerializerOptions() { WriteIndented = true});
Console.WriteLine(json);
class O {
[JsonInclude]
public int publicField = 1;
//[JsonInclude]
//This won't work and throws an exception
//'The non-public property 'privateField' on type 'O' is annotated with 'JsonIncludeAttribute' which is invalid.'
private int privateField = 2;
[JsonIgnore]
public int P1 { get; set;} = 3;
public int P2 { get; set; } = 4;
}
Run Code Online (Sandbox Code Playgroud)
这导致:
{
"P2": 4,
"publicField": 1
}
Run Code Online (Sandbox Code Playgroud)
或者你可以使用IncludeFields
var json = JsonSerializer.Serialize(new O(), new JsonSerializerOptions() { IncludeFields = true});
Run Code Online (Sandbox Code Playgroud)
(参考:包含字段)
| 归档时间: |
|
| 查看次数: |
244 次 |
| 最近记录: |