Saksham Srivastava
Saksham Srivastava

Reputation: 41

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

I have this API Response as a string.

/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

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.

Upvotes: 1

Views: 126

Answers (3)

Peter Csala
Peter Csala

Reputation: 22714

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 /
  2. Iterate through the parts by incrementing the loop variable with 2
  3. If the key is already present ignore that key-value pair
  4. Otherwise put the key value into the results collection

Upvotes: 1

IV.
IV.

Reputation: 9158

Consider parsing to an XElement object which offers the advantage of providing the means to act on the values received:

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

enter image description here

Upvotes: 1

David Osborne
David Osborne

Reputation: 6791

Building on @Jeroen Mostert's idea:

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. You should be able to do some more with that list though to get what you need.

Upvotes: 3

Related Questions