我无法访问 json.net 反序列化的所有 json 数据。 我怎样才能访问它。当我在控制台中 WriteLine 时它为空。
帐户.cs
public class Account
{
public string Email { get; set; }
public bool Active { get; set; }
public DateTime CreatedDate { get; set; }
public IList<string> Roles { get; set; }
}
主类
string json2 = @"{'Accounts' :[{
'Email': '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ed878c80889ead88958c809d8188c38e8280" rel="noreferrer noopener nofollow">[email protected]</a>',
'Active': true,
'CreatedDate': '2013-01-20T00:00:00Z',
'Roles': [
'User',
'Admin']
},
{
'Email': '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a0cac1cdc5d3e0c5d8c1cdd0ccc58ec3cfcd92" rel="noreferrer noopener nofollow">[email protected]</a>',
'Active': true,
'CreatedDate': '2013-01-20T00:00:00Z',
'Roles': [
'Userz',
'Adminz'
]
}]}";
List<Account> account = new List<Account>();
account.Add(JsonConvert.DeserializeObject<Account>(json2));
// <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="553f3438302615302d34382539307b363a38" rel="noreferrer noopener nofollow">[email protected]</a>
Console.Write(account[0].Email);
最佳答案
无法按照您想要的方式解析您拥有的 JSON 字符串。 Try this instead :
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
string json2 = @"[{
'Email': '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="761c171b130536130e171b061a135815191b" rel="noreferrer noopener nofollow">[email protected]</a>',
'Active': true,
'CreatedDate': '2013-01-20T00:00:00Z',
'Roles': [
'User',
'Admin']
},
{
'Email': '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="254f4448405665405d44485549400b464a4817" rel="noreferrer noopener nofollow">[email protected]</a>',
'Active': true,
'CreatedDate': '2013-01-20T00:00:00Z',
'Roles': [
'Userz',
'Adminz'
]
}]";
List<Account> account = new List<Account>();
account.AddRange(JsonConvert.DeserializeObject<List<Account>>(json2));
// <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3d575c50584e7d58455c504d5158135e5250" rel="noreferrer noopener nofollow">[email protected]</a>
Console.Write(account[0].Email);
}
}
public class Account
{
public string Email { get; set; }
public bool Active { get; set; }
public DateTime CreatedDate { get; set; }
public IList<string> Roles { get; set; }
}
编辑:或者实际上 @dotnetom 提供的答案解决了您的问题,以防您无法控制 json 格式
关于c# - 如何在c#中访问数据json.net数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33056540/