json array in hashmap using google gson

Your JSON is an array of objects, not anything resembling a HashMap.

If you mean you're trying to convert that to a List of HashMaps ... then that's what you need to do:

Gson gson = new Gson();
Type listType = new TypeToken<List<HashMap<String, String>>>(){}.getType();
List<HashMap<String, String>> listOfCountry = 
    gson.fromJson(sb.toString(), listType);

Edit to add from comments below:

If you would like to deserialize to an array of Country POJOs (which is really the better approach), it's as simple as:

class Country {
    public String countryId;
    public String countryName;
}
...
Country[] countryArray = gson.fromJson(myJsonString, Country[].class);

That said, it's really better to use a Collection:

Type listType = new TypeToken<List<Country>>(){}.getType();
List<Country> countryList = gson.fromJson(myJsonString, listType);

I assume you're trying to create a mapping of countryIds to countryNames, correct? This can be done in Gson, but really isn't what it is designed for. Gson is primarily intended translate JSON into equivalent Java objects (e.g. an array into a List, an object into an Object or a Map, etc.) and not for transforming arbitrary JSON into arbitrary Java.

If it's possible, the best thing for you to do would be to refactor your JSON. Consider the following format:

{
  "1": "India",
  "2": "United State"
}

It's less verbose, easier to read, and most notably, 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 your JSON syntax, you'll have to manually parse the JSON data into the structure you're trying to create, which will be somewhat tedious and involved. Best to read up on the Gson User Guide to learn how.

As an aside, you call your Map<String, String> object listOfCountry, which is a confusing name - is it a map or a list? Avoid using names like "list" for objects that aren't lists. In this case I would suggest either countries or countryMap.

Tags:

Java

Json

Gson