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

1 Answer 1

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
);
1
  • 1
    David thanks so much for the fast answer :) I've driven myself almost insane trying to figure this out today. Greatly appreciated Commented Jan 24, 2019 at 13:55

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.