首页 > 解决方案 > 从 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”或数组中的任何内容。

标签: c#json

解决方案


我建议不要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;

推荐阅读