如何用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
相关产品推荐
相关产品推荐

