如何在C#中从JObject获取特定值

时间:2019-01-29 13:54:20

标签: c# jobjectformatter

我需要从API响应中检索特定值。我的回答如下。如何获取每个包装的[productCodeScheme]值?

dynamic api = JObject.Parse(response.Content);

// api contains
{
    "operationCode": "12200000",
    "packs": [
        {
            "pack": {
                "productCodeScheme": "ppn",
                "productCode": "15000436574634",
                "serialNumber": "0000000001",
                "batchId": "00001",
                "expiryDate": "201201"
            },
            "result": {
                "operationCode": "61020008",
                "warning": "The product code is invalid."
            }
        },
        {
            "pack": {
                "productCodeScheme": "gs1",
                "productCode": "15000436574634",
                "serialNumber": "0000000002",
                "batchId": "00001",
                "expiryDate": "201201"
            },
            "result": {
                "operationCode": "11310300",
                "information": "The pack has been marked as stolen.",
                "state": "Stolen"
            }
        }
    ]
}

1 个答案:

答案 0 :(得分:0)

如果您希望对象保持动态,就可以这样做

awk -F'\t'

之后,您可以如下访问内部对象:

dynamic result = JsonConvert.DeserializeObject<dynamic>(response.Content);

但是,我强烈建议您将JSON响应反序列化为定义的对象,而不要使用foreach(dynamic item in result.packs) { string productCodeScheme = item.pack.productCodeScheme.ToString(); } dynamic既不安全又效率低下。您可以像下面的示例一样做某事,

dynamics

然后您可以像下面这样反序列化public class PackDetails { public string productCodeScheme { get; set; } public string productCode { get; set; } public string serialNumber { get; set; } public string batchId { get; set; } public string expiryDate { get; set; } } public class Result { public string operationCode { get; set; } public string warning { get; set; } public string information { get; set; } public string state { get; set; } } public class Pack { public PackDetails pack { get; set; } public Result result { get; set; } } public class ResponseObject { public string operationCode { get; set; } public List<Pack> packs { get; set; } } 并使用它

ResponseObject