AddNewtonsoftJson不能覆盖System.Text.Json

12

我把我的 .Net Core 版本从预览版 2 升级到了预览版 6,这导致了一些问题。最重要的是我不能再使用 newtonsoft JSON。

在 ConfigureServices 中添加 NewtonsoftJson 似乎没有任何作用,而新的 Json 序列化器似乎只能处理属性而非字段,并且无法识别 JSONIgnoreAttribute。

在 Startup 中的 ConfigureServices 方法中,我有以下代码:

services.AddMvc(x => x.EnableEndpointRouting = false).AddNewtonsoftJson();

但它似乎没有按照预期工作。在我的应用中,只有属性被序列化,而不是字段,同时 [JSONIgnore] 属性也没有起到作用。

我可以通过将需要的公共字段升级为属性来解决字段缺失的问题,但是我需要忽略一些字段。

是否有其他人遇到类似的问题?如何让新的 JSON 序列化器忽略某些属性并序列化公共字段,或者回退到 Newtonsoft?


1
我有完全相同的问题并在dotnet / core github上创建了一个问题。对于您的问题,也许可以使用[System.Text.Json.Serialization.JsonIgnore]代替使用Newtonsoft的JsonIgnore属性来解决问题。 - Drewman
对于 .NET Core 3.1,我唯一可用的方法是使用 DataContract/DataMember 属性。请参考 http://james.newtonking.com/archive/2009/10/23/efficient-json-with-json-net-reducing-serialized-json-size 或 https://dev59.com/J2kw5IYBdhLWcg3wDWTL。我在 .AddControllers 后添加了 AddNewtonsoftJson(),但 JsonIgnore 属性却被讽刺性地忽略了。 - itzJustKranker
1个回答

0

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;
}

这将导致:

{
  "P2": 4,
  "publicField": 1
}

或者你可以使用IncludeFields

var json = JsonSerializer.Serialize(new O(), new JsonSerializerOptions() { IncludeFields = true});

(参考:包括字段


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接