I assume that you are trying to create a mapping from countryId to countryName s, right? This can be done in Gson, but itβs not really what it is intended for. First of all, Gson translates JSON into equivalent Java objects (for example, an array into a list, an object into an object or map, etc.), and not to convert arbitrary JSON to arbitrary Java.
If possible, your best bet is to reorganize your JSON. Consider the following format:
{ "1": "India", "2": "United State" }
This is less verbose, easier to read and, most importantly, easy to parse with Gson:
Type countryMapType = new TypeToken<Map<Integer,String>>(){}.getType(); Map<Integer,String> countryMap = gson.fromJson(sb.toString(), countryMapType);
If you cannot edit the JSON syntax, you will have to manually parse the JSON data into the structure you are trying to create, which will be somewhat tedious and involved. It is best to read the Gson User Guide to find out how to do this.
As an aside, you call your Map<String, String> listOfCountry object, which is a confusing name - is it a map or a list? Avoid using names such as "list" for objects that are not lists. In this case, I would suggest either countries or countryMap .
source share