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

如何用C#的System.Text.Json移除JSON字符串中的嵌套元素

使用System.Text.Json移除JSON嵌套字段的简便方法

原始JSON结构:

{
  "card": {
    "number": "411111111111111111",
    "expirationMonth": null,
    "expirationYear": null,
    "securityCode": null
  }
}

需求很明确:只保留card下的number字段,移除expirationMonth、expirationYear、securityCode这三个嵌套字段。你之前的代码没生效,是因为直接在顶层JsonObject里调用Remove,但这些字段其实在嵌套的card对象里,根本没定位到正确的层级。

这里有几种简单的解决办法:

方法一:直接操作嵌套的JsonObject

先定位到card子对象,再删除目标字段:

using System.Text.Json;
using System.Text.Json.Nodes;

string jsonString = @"
{
  ""card"": {
    ""number"": ""411111111111111111"",
    ""expirationMonth"": null,
    ""expirationYear"": null,
    ""securityCode"": null
  }
}";

JsonObject requestJson = JsonSerializer.Deserialize<JsonObject>(jsonString);

// 先拿到嵌套的card对象
if (requestJson.TryGetPropertyValue("card", out JsonNode cardNode) && cardNode is JsonObject cardObj)
{
    cardObj.Remove("expirationMonth");
    cardObj.Remove("expirationYear");
    cardObj.Remove("securityCode");
}

// 转成清理后的JSON
string cleanedJson = requestJson.ToJsonString(new JsonSerializerOptions { WriteIndented = true });

方法二:用强类型模型(最简洁)

如果JSON结构固定,直接定义只包含需要字段的模型,序列化时自动忽略其他字段:

// 定义模型,只保留需要的字段
public class Card
{
    public string number { get; set; }
}

public class RootObject
{
    public Card card { get; set; }
}

// 序列化处理
RootObject root = JsonSerializer.Deserialize<RootObject>(jsonString);
string cleanedJson = JsonSerializer.Serialize(root, new JsonSerializerOptions { WriteIndented = true });

这种方式不需要手动删除字段,System.Text.Json会自动忽略模型中未定义的属性,代码最简洁。

方法三:用JsonDocument手动构建输出

如果不想修改原始对象,也可以直接遍历JSON元素,只写入需要的字段:

using System.Text.Json;
using System.IO;

string jsonString = @"
{
  ""card"": {
    ""number"": ""411111111111111111"",
    ""expirationMonth"": null,
    ""expirationYear"": null,
    ""securityCode"": null
  }
}";

using (JsonDocument doc = JsonDocument.Parse(jsonString))
{
    JsonElement root = doc.RootElement;
    using (var stream = new MemoryStream())
    using (var writer = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true }))
    {
        writer.WriteStartObject();
        writer.WritePropertyName("card");
        writer.WriteStartObject();
        // 只写入number字段
        writer.WriteString("number", root.GetProperty("card").GetProperty("number").GetString());
        writer.WriteEndObject();
        writer.WriteEndObject();
        writer.Flush();
        
        string cleanedJson = System.Text.Encoding.UTF8.GetString(stream.ToArray());
    }
}

内容的提问来源于stack exchange,提问作者Adam Williams

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 08:22:42