-4

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?

RalsD
  • 5
  • 3
  • 5
    You cannot model a dynamic object into a static class. The only way to parse that is as a `Dictionary>` (or create a class with all "continent" possibilities) – Camilo Terevinto Oct 20 '21 at 20:28
  • You can also use the `dynamic` data type https://stackoverflow.com/questions/3142495/deserialize-json-into-c-sharp-dynamic-object. You will lose all static type checking for any code that touches the `dynamic`, though. – omajid Oct 20 '21 at 22:28

2 Answers2

0

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

Serge
  • 40,935
  • 4
  • 18
  • 45
0

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);
}
Hazrelle
  • 758
  • 5
  • 9