I’ve a JSON which I retrieved from var responseMessage1 = await request1.Content.ReadAsStringAsync(); and looks like this : –
{
"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
}
}
How do I create a list of values inside the key description such that I can store it in a list like : –
var desc_list = ["Generate Plan","Stop Station"]
and I can iterate through it like
foreach(var item in desc_list)
{
//use item for xyz purpose
}
Which will output :
Generate Plan
Stop Station
>Solution :
Simple solution to do it convert JSON to C# objects and then iterate over Operation and read its Description property, as given below:
Root myDeserializedObject = JsonConvert.DeserializeObject<Root>(myJsonResponse);
foreach(var item in myDeserializedObject.operations)
{
Console.WriteLine(item.description);
}
Generate these C# object from JSON string from: 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; }
}