如何访问C#中的多组嵌套JSON元素



我收到了一个来自公共API的JSON,该JSON遵循以下结构。

[
{
"ID": "12345",
"company": [
{
"contract_ID": "abc5678",
"company": [
{
"company_name": "HelloWorld",
"company_logo": "HW",
"invested": "2000"
}
]
},
{
"contract_ID": "67891",
"company": [
{
"company_name": "GoodBye",
"company_logo": "GB",
"invested": "500"
}
]
},
{
"contract_ID": "32658",
"company": [
{
"company_name": "YesNo",
"company_logo": "YN",
"invested": "1500"
}
]
}
]
}
]

我尝试了几种不同的解析方法,无论是JTokens/JArrays还是各种类。以下内容允许我访问第一组值(company_name、company_logo、inverted(,但我无法迭代查找其他两个值。

//receiving the json data
var responseString = await response.Content.ReadAsStringAsync(); 
var fullJSON = JsonConvert.DeserializeObject(responseString);
Debug.Log(fullJSON);
//trying to parse it down to just the data I need
JToken token = JToken.Parse("{"root":" + responseString + "}");
Debug.Log(token);
JArray assets = (JArray)token.SelectToken("root[0].assets");
Debug.Log(assets);
JToken dig = JToken.Parse("{"root":" + assets + "}");
Debug.Log(dig);
JArray assetsNested = (JArray)dig.SelectToken("root[0].assets");
Debug.Log(assetsNested);

我的目标是提取contract_ID,然后提取相关的company_name、company_logo和投资项目。例如,abc5678、HelloWorld、HW和2000将是所需的三个数据集之一。

正确反序列化并保持代码可维护性的最简单方法是使用具体类。例如:

public sealed class Company
{
[JsonProperty("contract_ID")]
public string ContractID { get; set; }
[JsonProperty("company")]
public List<CompanyDefinition> CompanyDefinitions { get; set; }
}
public sealed class CompanyDefinition
{
[JsonProperty("company_name")]
public string CompanyName { get; set; }
[JsonProperty("company_logo")]
public string CompanyLogo { get; set; }
[JsonProperty("invested")]
public string Invested { get; set; }
}
public sealed class RootCompany
{
[JsonProperty("ID")]
public string ID { get; set; }
[JsonProperty("company")]
public List<Company> Company { get; set; }
}

然后,您只需反序列化即可。例如,如果你从一个文件中提取,你可以这样做:

using(var sr = new StreamReader(@"c:pathtojson.json"))
using(var jtr = new JsonTextReader(sr))
{
var result = new JsonSerializer().Deserialize<RootCompany[]>(jtr);
foreach(var r in result)
{
Console.WriteLine($"Company ID: {r.ID}");
foreach(var c in r.Company)
{
Console.WriteLine($"ContractID: {c.ContractID}");
foreach(var d in c.CompanyDefinitions)
{
Console.WriteLine($"Name: {d.CompanyName}");
Console.WriteLine($"Invested: {d.Invested}");
Console.WriteLine($"Company Logo: {d.CompanyLogo}");
}
}
}
}

当您的模型发生变化时,您不必费力地阅读一行又一行难以阅读的令牌选择代码。你只需要更新你的模型。

相关内容

  • 没有找到相关文章

最新更新