Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9246093
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T09:24:50+00:00 2026-06-18T09:24:50+00:00

I’m currently writing a c# wrapper library for an external REST API (which I

  • 0

I’m currently writing a c# wrapper library for an external REST API (which I have no control over), which returns JSON.

To deserializing the following JSON

{
    "countries": {
        "2": {
            "name": "Albania",
            "isoCode": "AL",
            "dialCode": "+355"
        },
        "3": {
            "name": "Algeria",
            "isoCode": "DZ",
            "dialCode": "+213"
        },
        "4": {
            "name": "American Samoa",
            "isoCode": "AS",
            "dialCode": "+1684"
        }
    }
}

I have a method GetCountries in my library which does the following:

public List<Country> GetCountries()
{
  string endpointUrl = GenerateEndPointUri(...)

  var countries = IssueApiGETRequest<CountriesWrapper>(endpointUrl);

  return countries.Countries.Select(x =>
  {
    x.Value.Id = x.Key;
    return x.Value;
  }).ToList();
}

The IssueAPIGetRequest look something like this:

private T IssueApiGETRequest<T>(string endPointUrl)
{
  using (var handler = new HttpClientHandler())
  {
    handler.Credentials = ...;

    using (HttpClient client = new HttpClient(handler))
    {
      var response = client.GetAsync(endPointUrl).Result;

      if (response.IsSuccessStatusCode)
      {
        string json = response.Content.ReadAsStringAsync().Result;
        var result = JsonConvert.DeserializeObject<T>(json);

        return result;
      }
      else
      {
        switch (response.StatusCode)
        {
          case HttpStatusCode.BadRequest:
            throw new InvalidParameterException("Invalid parameters");
        }
        throw new Exception("Unable to process request");
      }
    }
  }
}

This allows me to define a generic method for all the GET endpoints on the external API and have them serialized into my own defined types.

Then finally, I have these Class entities defined:

  [JsonObject(MemberSerialization = MemberSerialization.OptIn)]
  internal class CountriesWrapper
  {
    [JsonProperty(PropertyName = "countries")]
    public IDictionary<int, Country> Countries { get; set; }
  }

  [JsonObject(MemberSerialization = MemberSerialization.OptIn)]
  public class Country
  {
    public int Id { get; set; }

    [JsonProperty(PropertyName = "name")]
    public string Name { get; set; }

    [JsonProperty(PropertyName = "isoCode")]
    public string IsoCode { get; set; }

    [JsonProperty(PropertyName = "dialCode")]
    public string DialCode { get; set; }
  }

I’m not very happy with the GetCountries method, which has to reiterate over the Dictionary that is returned from the deserialization, and having the CountriesWrapper class.

QUESTION: I would like to know if I’m missing a trick or if someone can suggest a cleaner way of laying this out. Whilst keeping a generic method of issuing GET requests to the external API.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T09:24:51+00:00Added an answer on June 18, 2026 at 9:24 am

    This can be done with a JsonConverter similar like this answer

    I think It’s very the strange the json, anyway I implemented the Converter that can read that sort of json. I don’t think it’s well implemented but you can improve it

    class CountriesConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return (objectType == typeof(List<Country>));
        }
    
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var l = new List<Country>();
            dynamic expando = new ExpandoObject();
            var temp = expando as IDictionary<string, object>;
            if (reader.TokenType == JsonToken.StartObject)
            {
                var newCountry = true;
                while (reader.TokenType != JsonToken.EndObject)
                {
                    if(newCountry)
                        reader.Read();
                    if (reader.TokenType == JsonToken.PropertyName)
                    {
                        if (reader.Value != null && reader.Value.ToString() != "countries")
                        {
                            if (!temp.ContainsKey("Id"))
                            {
                                newCountry = true;
                                int id = 0;
                                if (Int32.TryParse(reader.Value.ToString(), out id))
                                    temp.Add("Id", id);
                            }
                            else
                            {
                                var propertyName = reader.Value.ToString();
                                reader.Read();
                                temp.Add(propertyName, reader.Value.ToString());
                            }
    
                        }
                    }
                    else if (reader.TokenType == JsonToken.EndObject)
                    {
                        l.Add(Country.BuildCountry(expando));
                        temp.Clear();
                        reader.Read();
                        newCountry = false;
                    }
                }
                reader.Read();
                while (reader.TokenType != JsonToken.EndObject)
                {
                    reader.Read();
                }
            }
    
            return l;
        }
    
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            //ToDo here we can decide to write the json as 
            //if only has one attribute output as string if it has more output as list
        }
    }
    

    And the country class, that it’s the same just de BuildCountry Method

    [JsonObject(MemberSerialization = MemberSerialization.OptIn)]
    public class Country
    {
        public int Id { get; set; }
    
        [JsonProperty(PropertyName = "name")]
        public string Name { get; set; }
    
        [JsonProperty(PropertyName = "isoCode")]
        public string IsoCode { get; set; }
    
        [JsonProperty(PropertyName = "dialCode")]
        public string DialCode { get; set; }
    
        internal static Country BuildCountry(dynamic expando)
        {
            return new Country
            {
                Id = expando.Id,
                Name = expando.name,
                IsoCode = expando.isoCode,
                DialCode = expando.dialCode
            };
    
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have an autohotkey script which looks up a word in a bilingual dictionary
I have an array which has BIG numbers and small numbers in it. I
I have a text area in my form which accepts all possible characters from
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am writing an app for my school newspaper, which is run completely online
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have just tried to save a simple *.rtf file with some websites and
I am confused How to use looping for Json response Array in another Array.
I am using JSon response to parse title,date content and thumbnail images and place

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.