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

如何使用System.Text.Json更新JSON属性值并保存回文件

如何使用System.Text.Json更新JSON属性值并保存回文件

我完全懂你这种感受——习惯了Newtonsoft.Json里SelectToken那种用点和数组下标就能轻松定位属性的便捷后,切换到System.Text.Json确实会有点无从下手。别担心,我们可以自己实现一套路径解析逻辑,搭配JsonNode来完成特定属性的更新,最后保存回文件。

下面是完整的实现方案,包含路径解析、属性更新和文件保存的全部逻辑:

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

private void UpdateJsonValue(string jsonFilePath, string propertyPath, object newValue)
{
    // 1. 读取文件中的JSON内容
    string jsonContent = File.ReadAllText(jsonFilePath);
    JsonNode? rootNode = JsonNode.Parse(jsonContent);
    if (rootNode == null)
        return;

    // 2. 解析属性路径,定位到目标节点
    JsonNode? targetNode = rootNode;
    string[] pathSegments = propertyPath.Split('.');
    
    foreach (string segment in pathSegments)
    {
        if (targetNode == null)
            break;

        // 处理数组下标,比如 "stars[0]"
        if (segment.Contains('['))
        {
            // 拆分数组名称和下标
            string arrayName = segment.Substring(0, segment.IndexOf('['));
            int index = int.Parse(segment.Substring(segment.IndexOf('[') + 1, segment.IndexOf(']') - segment.IndexOf('[') - 1));
            
            // 获取数组节点并定位到对应索引
            JsonArray? arrayNode = targetNode[arrayName] as JsonArray;
            targetNode = arrayNode?[index];
        }
        else
        {
            // 处理普通对象属性
            targetNode = targetNode[segment];
        }
    }

    // 3. 更新目标节点的值
    if (targetNode != null)
    {
        // 根据 newValue 的类型创建对应的 JsonNode
        JsonNode? valueNode = newValue switch
        {
            string str => JsonValue.Create(str),
            int intVal => JsonValue.Create(intVal),
            bool boolVal => JsonValue.Create(boolVal),
            double doubleVal => JsonValue.Create(doubleVal),
            _ => JsonNode.Parse(JsonSerializer.Serialize(newValue)) // 处理复杂类型
        };

        // 替换目标节点的值
        targetNode.ReplaceWith(valueNode);
    }

    // 4. 将更新后的JSON保存回文件
    if (rootNode != null)
    {
        string updatedJson = rootNode.ToJsonString(new JsonSerializerOptions { WriteIndented = true });
        File.WriteAllText(jsonFilePath, updatedJson);
    }
}

关键逻辑说明:

  • 路径解析:把类似"issue.title"或"stars[0].value"的路径拆分成片段,逐个处理对象属性和数组索引。
  • 数组处理:识别带下标的路径片段,拆分出数组名称和索引值,定位到数组中的对应元素。
  • 值更新:根据新值的类型创建对应的JsonNode,用ReplaceWith方法替换目标节点的内容。
  • 文件保存:将更新后的JsonNode序列化为格式化的JSON字符串,覆盖原文件内容。

使用示例:

假设你的JSON文件路径是"sample.json",可以这样调用方法:

// 更新issue的title
UpdateJsonValue("sample.json", "issue.title", "New Empowering Razor Club");

// 更新stars数组第一个元素的value
UpdateJsonValue("sample.json", "stars[0].value", 5);

这个方法可以适配你给定的固定JSON结构,只要路径格式正确,就能精准更新对应的属性值啦。

备注:内容来源于stack exchange,提问作者derodevil

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.15 15:44:36