You need to enable JavaScript to run this app. C#开发中如何从指定JSON消息提取code和message节点值
优惠活动
大模型
产品
解决方案
定价
更多

C#开发中如何从指定JSON消息提取code和message节点值

C# 从目标JSON提取code、message字段的实现方案

你要提取的两个字段在JSON中的访问路径为:根节点 → txn数组 → 第1个数组元素 → code/message属性,根据项目使用的JSON解析库,可直接套用以下实现:

  • 无强类型快速取值(适合临时调试、快速开发场景,无需提前定义实体类)
    • 基于.NET 内置System.Text.Json(.NET Core 3.0+/.NET 5+ 默认内置,无需额外安装包):
      // jsonStr 为接收到的原始JSON字符串
      using System.Text.Json;
      
      using var jsonDoc = JsonDocument.Parse(jsonStr);
      // 定位到txn数组的第一个元素
      var firstTxnNode = jsonDoc.RootElement.GetProperty("txn")[0];
      string code = firstTxnNode.GetProperty("code").GetString() ?? string.Empty;
      string message = firstTxnNode.GetProperty("message").GetString() ?? string.Empty;
      
    • 基于Newtonsoft.Json(Json.NET,.NET Framework 老项目常用):
      需先通过NuGet安装Newtonsoft.Json包,再按如下写法取值:
      using Newtonsoft.Json.Linq;
      
      var jsonObj = JObject.Parse(jsonStr);
      string code = (string?)jsonObj["txn"]?[0]?["code"] ?? string.Empty;
      string message = (string?)jsonObj["txn"]?[0]?["message"] ?? string.Empty;
      

    生产环境兼容提示:上述写法如果遇到txn数组为空、对应属性不存在的异常情况,需要补充长度判断、TryGetProperty校验逻辑,避免触发索引越界、键不存在的运行时异常。

  • 强类型反序列化取值(适合长期维护的业务代码,减少硬编码JSON路径带来的低级错误)
    首先根据JSON结构定义对应C#实体类:
    // 对应JSON根节点结构
    public class ApiResponse
    {
        public object? Status { get; set; }
        public object? Msg { get; set; }
        public List<TxnInfo> Txn { get; set; } = new();
    }
    
    // 对应txn数组内的单条元素结构
    public class TxnInfo
    {
        public string Code { get; set; } = string.Empty;
        public string Message { get; set; } = string.Empty;
        public string? Match { get; set; }
        public object? Name { get; set; }
        public string? Number { get; set; }
        public string? Id { get; set; }
    }
    
    反序列化后直接取值即可:
    var response = JsonSerializer.Deserialize<ApiResponse>(jsonStr);
    if (response?.Txn is { Count: > 0 })
    {
        string code = response.Txn[0].Code;
        string message = response.Txn[0].Message;
    }
    
    注意:如果JSON字段大小写和C#实体属性名不匹配,可以通过特性指定映射关系:
    • 用System.Text.Json时加[JsonPropertyName("code")]标记对应属性
    • 用Newtonsoft.Json时加[JsonProperty("code")]标记对应属性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.01 17:36:09