如何通过引用同一JSON中的另一个密钥来获得键的值?另外,如何将字符串添加到URI的末尾?

发布于 2025-02-03 20:15:47 字数 4919 浏览 4 评论 0原文

请参阅下面的JSON: -

{
    "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
    }
}

请在下面找到我的代码: -

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; }
}
}
}

问题#1

在交换机情况下,我想获取com_cumulocity_model and id的值在满足情况下(value_of_description)的情况下,同一JSON对象。 例如 : 如果案例“停止站”:得到满足,我想获取com_cumulocity_modelid 的等价值,即模式“:0,” stopStationPayload“:” [{\“ ControllerAddress \”:11,\“ stationAddress \”:26}]”} and 和“ 121985465”。必须将其与内部情况内的值进行比较,并基于此。

问题#2

我们如何添加id =“ 121985465”的值,我们在上面讨论的在case(“ stop Station”)中提出postasync请求的末尾 in Lines var httpclientStopstation = httpclientfactory.createclient(“ executePoerations”); var request4 =等待httpclientstopstation.postasync(“”);

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("");?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

冷了相思 2025-02-10 20:15:47

简短的方式。如果您只需要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());

结果

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

,但是如果您需要整个数据,则可以使用此代码进行测试。

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

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; }
}

如果您不需要,则可以从数据中删除统计信息类和统计属性 现在,您可以使用LINQ获取任何数据

,例如

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

结果(以JSON格式)

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

如何打印

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

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));

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文