如何从 JSON 响应的嵌套对象内的特定键创建列表?

How to create a list from a specific key inside the nested object of JSON response?

我有一个从 var responseMessage1 = await request1.Content.ReadAsStringAsync(); 中检索到的 JSON,看起来像这样:-

{
    "operations": [
        {
            "creationTime": "2022-06-02T10:28:28.765+03:00",
            "deviceId": "43432103",
            "deviceName": "P25-SC-0228",
            "status": "PENDING",
            "com_cumulocity_model": {
                "op": "s",
                "param": "waterStartDateTime",
                "value": "1/2/2018, 7:30:00 AM"
            },
            "description": "Generate Plan"
        },
        {
            "creationTime": "2022-06-02T10:28:36.276+03:00",
            "deviceId": "43432103",
            "deviceName": "P25-SC-0228",
            "status": "PENDING",
            "com_cumulocity_model": {
                "Mode": 0,
                "StopStationPayload": "[{\"ControllerAddress\":11,\"StationAddress\":26}]"
            },
            "description": "Stop Station"
        }
    ],
    "statistics": {
        "currentPage": 1,
        "pageSize": 5
    }
}

如何在键 description 中创建一个值列表,以便我可以将它存储在一个列表中,例如:-

var desc_list = ["Generate Plan","Stop Station"] 我可以像

一样遍历​​它
foreach(var item in desc_list)
{
  //use item for xyz purpose
}

这将输出:

Generate Plan
Stop Station

如果它只是你需要输出的描述,如果你需要存储它,我会创建一个List<>(大概它只需要是一个字符串)并为循环中的每个项目添加 item.description。然后你可以使用 list.ToString() 进行输出。

如果你不需要那么你应该可以做到Console.WriteLine(item.description);

编辑:从未见过另一个 JSON 对象。您可能需要指定为 item.operations.description

简单的解决方案,将 JSON 转换为 C# 对象,然后遍历操作并阅读其描述 属性,如下所示:

Root myDeserializedObject = JsonConvert.DeserializeObject<Root>(myJsonResponse);
foreach(var item in myDeserializedObject.operations)
{
   Console.WriteLine(item.description);
}

从 JSON 字符串生成这些 C# 对象:https://json2csharp.com/

public class ComCumulocityModel
{
    public string op { get; set; }
    public string param { get; set; }
    public string value { get; set; }
    public int? Mode { get; set; }
    public string StopStationPayload { get; set; }
}

public class Operation
{
    public DateTime creationTime { get; set; }
    public string deviceId { get; set; }
    public string deviceName { get; set; }
    public string status { get; set; }
    public ComCumulocityModel com_cumulocity_model { get; set; }
    public string description { get; set; }
}

public class Root
{
    public List<Operation> operations { get; set; }
    public Statistics statistics { get; set; }
}

public class Statistics
{
    public int currentPage { get; set; }
    public int pageSize { get; set; }
}

试试这个

var operations=JObject.Parse(json)["operations"];
string[] desc_list =operations.Select(o => (string) o["description"]).ToArray();

foreach(var item in desc_list) Console.WriteLine(item);

// Generate Plan
// Stop Station