Home > Software design >  How to parse in C# object the {"Europe":{"France":"Paris","UK&quo
How to parse in C# object the {"Europe":{"France":"Paris","UK&quo

Time:10-21

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

{
    "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?

CodePudding user response:

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

CodePudding user response:

try this

var json="{\"Europe\":{\"France\":\"Paris\",\"UK\":\"London\",\"Germany\":\"Berlin\"}}";

var result= JsonConvert.DeserializeObject<EuropeCountry>));

var continent = new Continent {
 Name = nameof( result.Europe),
 Countries = result.Europe.Select(e => new Country {Name=e.Key, Capital=e.Value} ).ToList()
};
 

public class Continent
{
    public string Name { get; set; }
    public List<Country> Countries { get; set; }
}

public class EuropeCountries
{
    public Dictionary<string, string> Europe {get;set;}
}

  • Related