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

如何用C#的Newtonsoft.Json从含数组的JSON中提取accountId

提取JSON中的accountId字段(C# + Newtonsoft.Json)

方法一:动态类型解析

无需预先定义实体类,直接逐层访问JSON节点:

using Newtonsoft.Json;
using System;

// 目标JSON字符串
string json = @"{""AccountListResponse"": {""Accounts"": {""Account"": [ {""accountId"":""0001"",""accountIdKey"":""key1"",""accountMode"":""ON""}, {""accountId"":""00021"",""accountIdKey"":""key21"",""accountMode"":""ON""}, {""accountId"":""00031"",""accountIdKey"":""key31"",""accountMode"":""ON""} ] } } }";

// 反序列化为动态对象
dynamic responseObj = JsonConvert.DeserializeObject(json);

// 遍历Account数组,提取accountId
foreach (var account in responseObj.AccountListResponse.Accounts.Account)
{
    Console.WriteLine(account.accountId);
}

方法二:强类型实体类解析

通过定义与JSON结构匹配的实体类,实现编译时类型检查,更适合生产环境:
首先定义对应实体类:

// 根对象
public class RootResponse
{
    public AccountListResponse AccountListResponse { get; set; }
}

public class AccountListResponse
{
    public AccountsContainer Accounts { get; set; }
}

public class AccountsContainer
{
    public Account[] Account { get; set; }
}

public class Account
{
    public string accountId { get; set; }
    public string accountIdKey { get; set; }
    public string accountMode { get; set; }
}

然后执行反序列化与提取:

using Newtonsoft.Json;
using System;

string json = @"{""AccountListResponse"": {""Accounts"": {""Account"": [ {""accountId"":""0001"",""accountIdKey"":""key1"",""accountMode"":""ON""}, {""accountId"":""00021"",""accountIdKey"":""key21"",""accountMode"":""ON""}, {""accountId"":""00031"",""accountIdKey"":""key31"",""accountMode"":""ON""} ] } } }";

// 反序列化为强类型对象
var root = JsonConvert.DeserializeObject<RootResponse>(json);

// 遍历数组提取accountId
foreach (var account in root.AccountListResponse.Accounts.Account)
{
    Console.WriteLine(account.accountId);
}

两种方法对比:

  • 动态类型:实现快速,无需编写实体类,但缺少编译时类型校验,适合临时调试或简单场景
  • 强类型:类型安全,有IDE智能提示,适合复杂业务场景和生产代码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 00:10:13