You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Dictionary<string, long>无法序列化问题求助

解决System.Text.Json序列化后返回空JSON的问题

你的问题出在System.Text.Json默认只序列化公共属性,不序列化公共字段,所以offer字段没有被纳入序列化范围,最终输出空的{}。

下面是两种可行的解决方法:

方法一:将字段改为属性(推荐)

这是符合C#封装规范的做法,把offer字段改成带get/set的属性:

public class Offer_RPC
{
    /// <summary>
    /// this dictionary contains your requested additions ans substractions, in mojos.<br/>
    /// if you wan to offer an nft for example, use the launcher id such as <br/>
    /// "1": 1000000000000 (offer for 1 xch) <br/>
    /// "cc4138f8debe4fbedf26ccae0f965be19c67a49d525f1416c0749c3c865dxxx", -1 <br/>
    /// </summary>
    public Dictionary<string, long> offer { get; set; } = new Dictionary<string, long>();

    public override string ToString()
    {
        JsonSerializerOptions options = new JsonSerializerOptions();
        options.WriteIndented = false;
        options.DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull;
        return JsonSerializer.Serialize(this, options);
    }
}

方法二:配置序列化选项以包含字段

如果无法修改字段定义,可以在序列化时开启IncludeFields选项,让序列化器处理公共字段:

public override string ToString()
{
    JsonSerializerOptions options = new JsonSerializerOptions();
    options.WriteIndented = false;
    options.DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull;
    // 开启公共字段序列化
    options.IncludeFields = true;
    return JsonSerializer.Serialize(this, options);
}

测试时,两种方法都能正确输出包含offer键值对的JSON,比如:{"offer":{"1":1,"2":-1}}

内容的提问来源于stack exchange,提问作者julian bechtold

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 19:36:12