Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json array in hashmap using google gson

Tags:

java

json

gson

I am new with Gson and I am trying to parse array of object in a Hashmap, but I am getting com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 3.

My code is

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

and JSON is

[
  {"countryId":"1","countryName":"India"},
  {"countryId":"2","countryName":"United State"}
]
like image 993
Jitendra Prajapati Avatar asked Jan 09 '14 07:01

Jitendra Prajapati


3 Answers

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);
like image 159
Brian Roach Avatar answered Sep 28 '22 03:09

Brian Roach


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.

like image 40
dimo414 Avatar answered Sep 28 '22 04:09

dimo414


After reading what @dimo414 and @Brian Roach said, if you still want to get a map out of your json structure, you can achieve by doing this:

Type type = new TypeToken<HashMap<String, String>>() {}.getType();
Gson gson = new GsonBuilder().registerTypeAdapter(type, new JsonDeserializer<HashMap<String, String>>() {

    @Override
    public HashMap<String, String> deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
        HashMap<String, String> map = new HashMap<>();

        for (JsonElement element : jsonElement.getAsJsonArray()) {
            JsonObject jsonObject = element.getAsJsonObject();

            signals.put(jsonObject.get("countryId").getAsString(), jsonObject.get("countryName").getAsString());
        }

        return map;
    }
}).create();

HashMap<String, String> countries = gson.fromJson(jsonArray, type);

But at that point you could just parse your json into a JsonArray and loop through it making your map.

like image 31
jairobjunior Avatar answered Sep 28 '22 02:09

jairobjunior