我有一个JSON,我从var responseMessage1 = await request1.Content.ReadAsStringAsync();
检索,看起来像这样:-
{
"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
将JSON转换为c#对象,然后遍历Operation并读取其Description属性的简单解决方案,如下所示:
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; }
}
try this
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
如果它只是您需要输出的描述,如果您需要存储它,我将创建一个List<>
(大概它只需要是一个字符串),并为循环中的每个项目添加item.description
。然后您可以使用list.ToString()
作为输出。
如果你不需要,那么你应该可以做Console.WriteLine(item.description);
编辑:从未见过其他JSON对象。您可能需要指定为item.operations.description