Search code examples
c#.netjson.netdotnet-httpclienthttpclientfactory

How to get value of a key by referencing another key in the same JSON?? Also how to add string to the end of uri?


Please refer to the JSON below : -

{
    "operations": [
        {
            "creationTime": "2022-06-02T10:28:28.765+03:00",
            "deviceId": "43432103",
            "deviceName": "P25-SC-0228",
            "id": "121985460",
            "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",
            "id": "121985465",
            "status": "PENDING",
            "com_cumulocity_model": {
                "Mode": 0,
                "StopStationPayload": "[{\"ControllerAddress\":11,\"StationAddress\":26}]"
            },
            "description": "Stop Station"
        }
    ],
    "statistics": {
        "currentPage": 1,
        "pageSize": 5
    }
}

Please find my code below : -

namespace handleDeviceOperations
{
    
class Program
{

string operationID = String.Empty;
static async Task Main(string[] args)
{
    var serviceCollection = new ServiceCollection();
    ConfigureServices(serviceCollection);
    var services = serviceCollection.BuildServiceProvider();
    var httpClientFactory = services.GetRequiredService<IHttpClientFactory>();

    var httpClientGetOperations = httpClientFactory.CreateClient("getOperations");
    var request1 = await httpClientGetOperations.GetAsync("");

    if (request1.IsSuccessStatusCode)
    {
        var responseMessage1 = await request1.Content.ReadAsStringAsync();
        JObject obj = JObject.Parse(responseMessage1);
        var root = JsonConvert.DeserializeObject<RootObject>(responseMessage1);

        RootObject myDeserializedObject = JsonConvert.DeserializeObject<RootObject>(responseMessage1);
        
        if (obj["operations"].HasValues)
        {
            foreach(var item in myDeserializedObject.operations)
            {
                switch(item.description)
                {
                    case "Generate Plan":
                        var gen_plan=JObject.Parse(responseMessage1)["operations"];
                        string[] gen_plan_list_operationID =gen_plan.Select(o => (string) o["id"]).ToArray();
                        JObject[] gen_plan_list_payload = gen_plan.Select(o => (JObject) o["com_cumulocity_model"]).ToArray();
                        break;

                    case "Stop Station":
                        var stop_st=JObject.Parse(responseMessage1)["operations"];
                        string[] stop_st_list_operationID =stop_st.Select(o => (string) o["id"]).ToArray();
                        JObject[] stop_st_list_payload = stop_st.Select(o => (JObject) o["com_cumulocity_model"]).ToArray();

                        var httpClientStopStation = httpClientFactory.CreateClient("executeOperations");
                        var request4 = await httpClientStopStation.PostAsync("");
                        break;
                }
            }
        }
    }
}

private static void ConfigureServices(ServiceCollection services)
{

    services.AddHttpClient("getOperations", options =>
    {
        options.BaseAddress = new Uri("https://myurl.com?deviceId=43432103");

        options.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic","auth value");
    });

    services.AddHttpClient("executeOperations", options =>
    {
        options.BaseAddress = new Uri("https://myurl.com/"+operationID);
        options.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic","auth value");
        options.DefaultRequestHeaders.Add("Accept", "application/vnd.com.nsn.xyz.operation+json");
    });
    
}
public class RootObject
{
    public List<operation> operations { get; set; }
}
public class operation
{
    public golfController com_cumulocity_model { get; set; }
    public string description {get; set;}
}
public class golfController
{
    public int mode { get; set; }
    public string StopStationPayload { get; set; }
}
}
}

Question #1

In the switch case I want to fetch the value of com_cumulocity_model and id which belongs to the same JSON Object where case(value_of_description) is satisfied. For example : If case "Stop Station": is satisfied, I want to fetch the equivalent value of com_cumulocity_model and id inside it i.e. {"Mode": 0,"StopStationPayload": "[{\"ControllerAddress\":11,\"StationAddress\":26}]"} and "121985465" respectively. It must be compared to the value inside case and fetched on based of that.

Question #2

How do we add this value of id = "121985465" which we discussed above to the end of th url for making PostAsync request inside case("Stop Station") in lines var httpClientStopStation = httpClientFactory.CreateClient("executeOperations"); var request4 = await httpClientStopStation.PostAsync("");?


Solution

  • Short way. If you need just com_cumulocity_model

    var operations = JObject.Parse(json)["operations"];
    
    var com_cumulocity_model = operations.Where(o => (string) o["description"] == "Stop Station")
    .Select(o => o["com_cumulocity_model"])
    .FirstOrDefault();
    
    Console.WriteLine(com_cumulocity_model.ToString());
    

    result

    {
      "Mode": 0,
      "StopStationPayload": "[{\"ControllerAddress\":11,\"StationAddress\":26}]"
    }
    

    But if you need the whole data you can use this code for deserializing json.

    var data = JsonConvert.DeserializeObject<Data>(json);
    

    classes

    public class Data
    {
        public List<Operation> operations { get; set; }
        public Statistics statistics { 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 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 Statistics
    {
        public int currentPage { get; set; }
        public int pageSize { get; set; }
    }
    

    you can just remove Statistics class and statitics property from Data if you dont need it. The same about another properties

    Now you can use Linq to get any data, for example

    ComCumulocityModel com_cumulocity_model = data.operations
    .Where(o => o.description == "Stop Station")
    .Select(o => o.com_cumulocity_model)
    .FirstOrDefault();
    

    result (in json format)

    {
      "Mode": 0,
      "StopStationPayload": "[{\"ControllerAddress\":11,\"StationAddress\":26}]"
    }
    

    how to print

        var jsonSettings = new JsonSerializerSettings
        {
            NullValueHandling = NullValueHandling.Ignore,
            Formatting=Newtonsoft.Json.Formatting.Indented
        };
        Console.WriteLine(JsonConvert.SerializeObject(  com_cumulocity_model,  jsonSettings));