简体   繁体   English

如何从 C# 中的字符串中获取下一个值?

[英]How to Get the Next value from a string in c#?

I have this API Response as a string.我将此 API 响应作为字符串。

/subscriptions/5e5c4cca-75b4-412d-96a1-45a9446ef08c/resourcegroups/ft-us-point-dev/providers/microsoft.datafactory/factories/ftadfqpb/providers/Microsoft.ResourceHealth/availabilityStatuses/current

Response object look like this :响应对象如下所示:

{
            "id": "/subscriptions/5e5c4cca-75b4-412d-96a1-45a9446ef08c/resourcegroups/ft-us-point-dev/providers/microsoft.purview/accounts/ft-ue-pdc-dev-purview/providers/Microsoft.ResourceHealth/availabilityStatuses/current",
            "name": "current",
            "type": "Microsoft.ResourceHealth/AvailabilityStatuses",
            "location": "eastus",
            "properties": {
                "availabilityState": "Unknown",
                "title": "Unknown",
                "summary": "We are currently unable to determine the health of this Azure Purview.",
                "reasonType": "",
                "occuredTime": "2022-05-24T08:10:58.4372995Z",
                "reasonChronicity": "Transient",
                "reportedTime": "2022-05-24T08:10:58.4372995Z"
            }

Now, I need each and every value from this response.现在,我需要此响应中的每一个值。 For Example, subscriptions value as 5e5c4cca-75b4-412d-96a1-45a9446ef08c, resourcegroups value as ft-us-point-dev, providers value as microsoft.datafactory, factories value as ftadfqpb例如,subscriptions 值为 5e5c4cca-75b4-412d-96a1-45a9446ef08c,resourcegroups 值为 ft-us-point-dev,providers 值为 microsoft.datafactory,factories 值为 ftadfqpb

How can I store these value so if in future if the api response has one or more values , my code is not affected by that.我如何存储这些值,所以如果将来如果 api 响应有一个或多个值,我的代码不会受此影响。

Building on @Jeroen Mostert 's idea:基于@Jeroen Mostert的想法:

var pairs = 
   @"/subscriptions/5e5c4cca-75b4-412d-96a1-45a9446ef08c/resourcegroups/ft-us-point-dev/providers/microsoft.purview/accounts/ft-ue-pdc-dev-purview/providers/Microsoft.ResourceHealth/availabilityStatuses/current"
      .Split('/', StringSplitOptions.RemoveEmptyEntries)
      .Chunk(2)
      .Select(s => (key: s[0], value: s[1]))
      .ToList();

Gets you a list of pairs.为您提供配对列表。 It can't be a dictionary as there are two providers .它不能是字典,因为有两个providers You should be able to do some more with that list though to get what you need.你应该可以用那个列表做更多的事情来得到你需要的东西。

Consider parsing to an XElement object which offers the advantage of providing the means to act on the values received:考虑解析为XElement对象,该对象具有提供对接收到的值进行操作的方法的优势:

XElement xel = new XElement("id");
var id = deserialized.id;
var parse = id.TrimStart(new char[]{'/'}).Split('/');
for (int key = 0; key < parse.Length; key+=2)
{
    var value = key + 1;
    if (key < parse.Length)
    {
        xel.Add(new XElement(parse[key], parse[value]));
    }
    else System.Diagnostics.Debug.Assert(false, "Mismatched pair.");
}

Test runner:测试跑者:

using System;
using System.Collections.Generic;
using System.Xml.Linq;
using Newtonsoft.Json;

namespace json_model
{
    class Program
    {
        static void Main(string[] args)
        {
            Model deserialized = JsonConvert.DeserializeObject<Model>(json);

            // [Prelim] Requires further testing
            XElement xel = new XElement("id");
            var id = deserialized.id;
            var parse = id.TrimStart(new char[]{'/'}).Split('/');
            for (int key = 0; key < parse.Length; key+=2)
            {
                var value = key + 1;
                if (key < parse.Length)
                {
                    xel.Add(new XElement(parse[key], parse[value]));
                }
                else System.Diagnostics.Debug.Assert(false, "Mismatched pair.");
            }
            Console.WriteLine(xel.ToString());
            Console.WriteLine();

            // An XElement is simple to search on and iterate.
            Console.WriteLine("Processing:");
            foreach (var element in xel.Elements("providers"))
            {
                Console.WriteLine($"'{(string)element}' is a Provider");
            }
        }
        class Model
        {
            public string id { get; set; }
            public string name { get; set; }
            public Dictionary<string, string> properties { get; set; }
        }

        const string json = @"{
            ""id"": ""/subscriptions/5e5c4cca-75b4-412d-96a1-45a9446ef08c/resourcegroups/ft-us-point-dev/providers/microsoft.purview/accounts/ft-ue-pdc-dev-purview/providers/Microsoft.ResourceHealth/availabilityStatuses/current"",
            ""name"": ""current"",
            ""type"": ""Microsoft.ResourceHealth/AvailabilityStatuses"",
            ""location"": ""eastus"",
            ""properties"": {
                ""availabilityState"": ""Unknown"",
                ""title"": ""Unknown"",
                ""summary"": ""We are currently unable to determine the health of this Azure Purview."",
                ""reasonType"": """",
                ""occuredTime"": ""2022-05-24T08:10:58.4372995Z"",
                ""reasonChronicity"": ""Transient"",
                ""reportedTime"": ""2022-05-24T08:10:58.4372995Z""
            }
        }";
    }
}

在此处输入图像描述

var responseId = "/subscriptions/5e5c4cca-75b4-412d-96a1-45a9446ef08c/resourcegroups/ft-us-point-dev/providers/microsoft.purview/accounts/ft-ue-pdc-dev-purview/providers/Microsoft.ResourceHealth/availabilityStatuses/current";
var parts = responseId.Substring(1).Split("/");
var results = new Dictionary<string, string>();
for(int keyIdx = 0; keyIdx < parts.Length; keyIdx += 2)
{
    if(!results.ContainsKey(parts[keyIdx]))
        results.Add(parts[keyIdx], parts[keyIdx + 1]);
}
  1. Either call .Split('/').Skip(1) or .Substring(1).Split('/') to get rid of the leading /调用.Split('/').Skip(1).Substring(1).Split('/')以摆脱前导/
  2. Iterate through the parts by incrementing the loop variable with 2通过将循环变量增加 2 来迭代各个parts
  3. If the key is already present ignore that key-value pair如果键已经存在,则忽略该键值对
  4. Otherwise put the key value into the results collection否则将键值放入results集合

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM