Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to loop attributes in a JSON string post converting it into C# object?

I have a below json, I want to loop the items inside the attribute CheckingUrls.

{
  "Root": {
    "Urls": {
      "CheckingUrls": [
        {
          "API Management": {
            "url": ".azure-api.net",
            "displayurl": "*.azure-api.net"
          },
          "Log Analytics": {
            "url": "1.ods.opinsights.azure.com",
            "displayurl": "*.ods.opinsights.azure.com"
          }
        }
      ]
    }
  }
}

Here are the C# class

public class Root
{
   Urls Urls { get; set; }
}


public class Urls 
{
   public List<CheckingUrls> CheckingUrls { get; set; }
}


public class CheckingUrls
{
    [JsonProperty("API Management")]
    public UrlDetails APIManagement { get; set; }

    [JsonProperty("Log Analytics")]
    public UrlDetails LogAnalytics { get; set; }

}

public class UrlDetails
{
    [JsonProperty("url")]
    public string url { get; set; }

    [JsonProperty("displayurl")]
    public string displayurl { get; set; }
}

I am trying to convert it into c# object using the below code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    var content = File.ReadAllText(jsonstring);
    var settings = JsonConvert.DeserializeObject<Root>(content); 

I am getting APIManagement and LogAnalytics as properties in the result. Is it possible to get these as List, so that I can loop the contents without hardcoding the properties in code.

Why I need solution: We might add new child to CheckingUrls and we do not want to change the c# code everytime when we change JSON.

>Solution :

Use a C# Dictionary when you want to convert a JSON Object to C# when you don’t have a concrete type. CheckingUrls is already an array, so you end up with

public List<Dictionary<string, UrlDetails>> CheckingUrls { get; set; }

The key of a Dictionary entry is the property name in the array element (like "API Management"), and the value is the object that contains the url and displayurl properties.

This eliminates the need for the CheckingUrls C# class.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading