Search code examples
c#jsondictionarystructurejson-deserialization

deserialize complex json into dictionary like structure


hi ive got a json file. that i can modify . but i need to access by its name. i need to access it like this

var result = sitelang.brands["en"] ;      // or
var result = sitelang.["brands"]["en"] ; 

did i make it understandable . im non native sorry for mistakes.
than you in advance .
and good luck!! with your projects.

EDİT real json file

{
"Brands": [
{
  "en": "Brands",
  "tr": "Markalar",
  "de": "Marken",
  "bg": "Производител",
  "el": "μάρκες",
  "uk": "бренди",
  "nl": "Merken",
  }
],
"Products": [
{
  "en": "Products",
  "tr": "Ürünler",
  "de": "Produkte",
  "bg": "Продукти",
  "el": "προϊόντα",
  "uk": "продукти",
  "nl": "producten",
  }
   ],
 "Search_Results": [
  {
  "en": "Arama Sonuçları",
  "tr": "Search Results",
  "de": "Suchergebnisse",
  "bg": "Резултати от търсенето",
  "el": "Αποτελέσματα Αναζήτησης",
  "uk": "Результати пошуку",
  }
 ],
}

Solution

  • You can use Json.NET to parse the JSON without declaring classes ahead and then convert it into a dictionary using LINQ:

    var root = (JObject) JsonConvert.DeserializeObject(json);
    var brands = root["Brands"]
      .AsJEnumerable()
      .First()
      .AsJEnumerable()
      .Cast<JProperty>()
      .ToDictionary(j => j.Name, j => j.Value);
    

    To lookup the translation of a specific brand simply use the dictionary:

    var translatedName = brands["en"];
    

    Replace the "Brands" string with "Product" or "Search_Results" to create the other two dictionaries.

    From your comment I can understand that you have many translations. In that case you can create a dictionary of dictionaries:

    var root = (JObject) JsonConvert.DeserializeObject(json);
    var dictionary = root
      .AsJEnumerable()
      .Cast<JProperty>()
      .ToDictionary(
        j => j.Name,
        j => j.Value
          .AsJEnumerable()
          .First()
          .AsJEnumerable()
          .Cast<JProperty>()
          .ToDictionary(k => k.Name, k => k.Value)
      );
    

    And get the translated name like this:

    var translatedName = dictionary["Brands"]["tr"];