c# - 从 JSON 数组中获取特定的 JSON 数据
问题描述
我有一个从 XML 转换的 JSON 数组,我想知道如何获取该 JSON 的一部分。
从我发现的另一个答案
var result =
JObject.Parse(jsonResult).Children().Children().Children().ElementAt(1).Children().First();
但这只是让我获得了 JSON 的一部分,并且很难弄清楚如何获得其他部分。
这是我从上面的代码中得到的部分
http://www.w3.org/2001/XMLSchema-instance
这是 JSON
{
"soap12:Envelope": {
"@xmlns:soap12": "http://www.w3.org/2003/05/soap-envelope",
"@xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"@xmlns:xsd": "http://www.w3.org/2001/XMLSchema",
"soap12:Body": {
"ProcessRequestResponse": {
"@xmlns": "http://localhost/TestServices",
"ProcessRequestResult": {
"StatusCode": "None or GE or PE or PW or NP or FS or NA or GF",
"Success": "boolean",
"Errors": {
"Error": [
{
"Code": "int",
"ErrorText": "string",
"ErrorType": "None or Critical or Non_Critical",
"Severity": "Warning or Error"
},
{
"Code": "int",
"ErrorText": "string",
"ErrorType": "None or Critical or Non_Critical",
"Severity": "Warning or Error"
}
]
}
}
}
}
}
}
我希望能够获得“StatusCode”或“Success”或数组中的任何内容。
解决方案
我建议不要JObject.Parse
直接使用,而是直接反序列化到您自己的类层次结构。例如,使用这样一组简单的类:
public class SoapObject
{
[JsonProperty("soap12:Envelope")]
public SoapData Envelope { get; set; }
}
public class SoapData
{
[JsonProperty("soap12:Body")]
public SoapBody Body { get; set; }
}
public class SoapBody
{
public ProcessRequestResponse ProcessRequestResponse { get; set; }
}
public class ProcessRequestResponse
{
public ProcessRequestResult ProcessRequestResult { get; set; }
}
public class ProcessRequestResult
{
public string StatusCode { get; set; }
public string Success { get; set; }
}
您可以简单地反序列化:
var soapObject = JsonConvert.DeserializeObject<SoapObject>(jsonResult);
现在您可以对所需的属性进行强类型访问:
var statusCode = soapObject.Envelope.Body
.ProcessRequestResponse.ProcessRequestResult.StatusCode;
推荐阅读
- java - 升级到 Spring Boot 2.1.3 后 Spring Data 查询性能问题
- bash - 在其中使用带有字母“a”的字符集会导致某些目录中出现意外行为
- python - Reportlab中Matplotlib上不完整的刻度标签
- sql - 如何在 include 中插入 Distinct 和 Order?
- javascript - 即使有一个单例类管理购物车状态,购物车中的元素总数也不会刷新
- javascript - Highchart 中的线条着色需要很长时间
- swift - 如何在 macOS 中无错误地访问联系人
- r - 因素分析未分配给对象
- c# - 在 C# 的 MongoDB Filter Builders 中,有没有办法过滤比较多个字段?
- vue.js - 如何将帖子从一个组件转移到另一个组件?