相关疑难解决方法(0)

如何使Json.Net跳过空集合的序列化

我有一个对象,其中包含几个属性,这些属性是字符串列表List<String>或字符串字典Dictionary<string,string>.我想使用Json.net将对象序列化为json,我希望生成最少量的文本.

我使用DefaultValueHandling和NullValueHandling将默认值设置为字符串和整数.但是,如果将DefaultValueHandling初始化为空List<String>Dictionary<string,string>?,则如何定义DefaultValueHandling以忽略序列化输出中的属性?

一些示例输出是:

{
 "Value1": "my value",
 "Value2": 3,
 "List1": [],
 "List2": []
}
Run Code Online (Sandbox Code Playgroud)

我想得到一个忽略上例中两个列表的结果,因为它们被设置为空列表的默认值.

任何帮助将不胜感激

c# asp.net serialization json.net

9
推荐指数
2
解决办法
7637
查看次数

序列化为json时如何忽略空列表?

我试图弄清楚如何序列化为 json 对象并跳过序列化值为空列表的属性。 我没有使用 Newtonsoft json

using System.Text.Json;
using System.Text.Json.Serialization;
using AutoMapper;
Run Code Online (Sandbox Code Playgroud)

我有一个带有属性的对象。

[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
[JsonPropertyName("extension")]
public List<Extension> Extension { get; set; }
Run Code Online (Sandbox Code Playgroud)

当我尝试使用以下命令序列化该对象时

var optionsJson =   new JsonSerializerOptions
    {
    WriteIndented = true,
    IgnoreNullValues = true,
    PropertyNameCaseInsensitive = true,
    };

var json = JsonSerializer.Serialize(report, optionsJson);
Run Code Online (Sandbox Code Playgroud)

它仍然给我一个空数组:

"extension": [],
Run Code Online (Sandbox Code Playgroud)

有没有办法阻止它序列化这些空列表?我愿意看到extension消失。它根本不应该存在。我需要这样做,因为如果我发送以下内容,网关将响应错误:

"extension": null,
Run Code Online (Sandbox Code Playgroud)

序列化时它不能是对象的一部分。

网关错误

我不想要这些空列表的原因是我发送到对象到空列表的第三方网关

"severity": "error", "code": "processing", "diagnostics": "数组不能为空 - 如果属性没有值,则不应存在", "location": [ "Bundle.entry[2 ].resource.extension", "第 96 行,第 23 栏"]

我试图避免对此进行某种令人讨厌的字符串替换。

c# json system.text.json .net-6.0

9
推荐指数
1
解决办法
7324
查看次数

.NET Core 3 中不会触发 shouldSerialize 方法

我通常ShouldSerialize用来排除没有数据的属性,例如数组,但现在,当我只在.NET Core 3. 它在使用时被触发,NewtonSoft但我已将它从我的项目中删除,因为它似乎不再需要。

例如:

    private ICollection<UserDto> _users;

    public ICollection<UserDto> Users
    {
        get => this._users ?? (this._users = new HashSet<UserDto>());
        set => this._users = value;
    }

    public bool ShouldSerializeUsers()
    {
        return this._users?.Count > 0;
    }
Run Code Online (Sandbox Code Playgroud)

为什么没有触发 ShouldSerializeUsers 的任何想法?

我已经看到其他可以使用的答案:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc()
        .AddJsonOptions(options => { 
        options.SerializerSettings.NullValueHandling = 
        NullValueHandling.Ignore;
    });
}
Run Code Online (Sandbox Code Playgroud)

但我想知道是否有另一种方法来处理这个问题,因为我没有使用 .AddMvc

谢谢。

c# serialization json asp.net-core asp.net-core-webapi

4
推荐指数
2
解决办法
1667
查看次数