Search code examples
c#jsonobjectdto

How to parse in C# object the {"Europe":{"France":"Paris","UK":"London","Germany":"Berlin"}} Json object where the keys are actual object values?


Update: I think I have to rephrase the question: I'm getting the continent, country and capital lists from lets say a db source and I have to construct a JSON object that has the given structure.

I have to create a Dto object that represents the following JSON object format:

{
    "Europe":{ 
        "France":"Paris",
        "UK":"London",
        "Germany":"Berlin"
    }
 } 

where "Europe" is a value for an object of type Continent and "France", "UK" and "London" are values of the object Country:

public class Country
{
   public string Name { get; set; }
   public string Capital { get; set; }
}

How would you represent that JSON object with object classes?


Solution

  • Use a proxy Dictionary<string, Dictionary<string, string>> as suggested by @ Camilo-Terevinto

    using System.Text.Json.Serialization;
    using System.Text.Json;
    
    public class Continent
    {
      public string Name { get; set; }
      public List<Country> Countries { get; set; } = new List<Country>();
    }
    
    public class Country
    {
      public string Name { get; set; }
      public string Capital { get; set; }
    }
    
    string json = @"
    {
        ""Europe"":{ 
            ""France"":""Paris"",
            ""UK"":""London"",
            ""Germany"":""Berlin""
        }
    }
    ";
    
    var dic = JsonSerializer.Deserialize<Dictionary<string,Dictionary<string,string>>>(json);
    
    var continents = new List<Continent>();
    
    foreach(var key in dic.Keys) {
      var continent = new Continent() { Name = key };
      foreach(var subkey in dic[key].Keys)
      {
        continent.Countries.Add(new Country() { Name = subkey, Capital = dic[key][subkey] });
      }
      continents.Add(continent);
    }