0

Im trying to parse the below JSON response:

{  
      "preferredLanguage":"en",
      "preferredLocale":"en_GB",
      "languages":{  
         "en":{  
            "langCountry":"en-bn",
            "defaultLang":"en_GB"  
         }
      }
}

I can do this successfully if I create 3 classes with the third called 'en'. However I would like to avoid this as there may be other languages besides English. Is there a way to specify a key of 'en' to return the data within the 'en' object? I have tried JSON.deserialiseUntyped with Maps of String, Object but I just get the error: System.TypeException: Invalid conversion from runtime type List<ANY> to Map<String, Object>

Here is the working class structure where I have hardcoded the class name "En":

public class countryLocale {
    public String preferredLanguage;
    public String preferredLocale;
    public Languages languages;

public class En {   
    public String langCountry;
    public String defaultLang;

}

public class Languages {
    public En en;
}

Thanks in advance

6

I think you can address this effectively with a mix of collections and custom classes, like this:

public class countryLocale {
    public String preferredLanguage;
    public String preferredLocale;
    public Map<String, Locale> languages;
}
public class Locale {   
    public String langCountry;
    public String defaultLang;
}

That saves you from having to model each language statically as a property in a Languages class. Then, you can deserialize the data by doing

countryLocale l = (countryLocale)JSON.deserialize(
    jsonstr, 
    countryLocale.class
);
| improve this answer | |
  • 1
    David thanks so much for the fast answer :) I've driven myself almost insane trying to figure this out today. Greatly appreciated – Jay Jan 24 '19 at 13:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.