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

如何为已有JSON中TestData数组的每个对象添加属性?

为JSON中TestData数组的每个对象添加属性

给定原始JSON:

{
    "Name": "testeName",
    "type": "unique",
    "TestData": [{
        "price": 2.3
    }]
}

目标是给TestData数组内的每个对象新增"type":"unique"属性,以下是两种简洁的实现方式:


方法一:直接操作JsonDocument(无需定义类)

利用System.Text.Json的JsonDocument和Utf8JsonWriter高效修改,避免冗余代码:

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

// 原始JSON字符串
string originalJson = @"{
    ""Name"": ""testeName"",
    ""type"": ""unique"",
    ""TestData"": [{
        ""price"": 2.3
    }]
}";

using JsonDocument doc = JsonDocument.Parse(originalJson);
using MemoryStream ms = new MemoryStream();
using Utf8JsonWriter writer = new Utf8JsonWriter(ms, new JsonWriterOptions { Indented = true });

writer.WriteStartObject();
foreach (JsonProperty prop in doc.RootElement.EnumerateObject())
{
    if (prop.Name == "TestData" && prop.Value.ValueKind == JsonValueKind.Array)
    {
        writer.WritePropertyName("TestData");
        writer.WriteStartArray();
        // 遍历数组内的每个对象
        foreach (JsonElement item in prop.Value.EnumerateArray())
        {
            writer.WriteStartObject();
            // 先写入原对象的所有属性
            foreach (JsonProperty itemProp in item.EnumerateObject())
            {
                itemProp.WriteTo(writer);
            }
            // 添加新属性
            writer.WriteString("type", "unique");
            writer.WriteEndObject();
        }
        writer.WriteEndArray();
    }
    else
    {
        // 直接写入其他属性
        prop.WriteTo(writer);
    }
}
writer.WriteEndObject();

// 获取最终JSON字符串
string resultJson = Encoding.UTF8.GetString(ms.ToArray());
Console.WriteLine(resultJson);

方法二:强类型序列化(更易维护)

如果JSON结构固定,定义对应实体类会更直观且不易出错:

using System.Text.Json;
using System.Collections.Generic;

// 定义实体类
public class Root
{
    public string Name { get; set; }
    [JsonPropertyName("type")]
    public string Type { get; set; }
    public List<TestDataItem> TestData { get; set; }
}

public class TestDataItem
{
    public double Price { get; set; }
    [JsonPropertyName("type")]
    public string Type { get; set; } // 新增属性
}

// 反序列化原始JSON
string originalJson = @"{
    ""Name"": ""testeName"",
    ""type"": ""unique"",
    ""TestData"": [{
        ""price"": 2.3
    }]
}";
Root root = JsonSerializer.Deserialize<Root>(originalJson);

// 为每个TestData对象设置Type属性
foreach (var item in root.TestData)
{
    item.Type = "unique";
}

// 序列化回JSON
string resultJson = JsonSerializer.Serialize(root, new JsonSerializerOptions { WriteIndented = true });
Console.WriteLine(resultJson);

原代码的错误分析

你的代码报错主要有两个原因:

  1. 判断条件错误:你判断的是element.Name == "price",但实际需要处理的是TestData属性,这个条件永远不会触发,导致逻辑完全错误。
  2. 写入顺序错误:即使条件正确,你先调用WriteStartObject,然后写入type属性,再调用testDataElement.WriteTo(writer)——这会把整个原对象(包括{})直接写入,导致JSON结构嵌套错误,从而抛出InvalidOperationException。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 03:57:23