10

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"}
]
2
  • Perhaps you could provide an example of the Map structure you'd like to end up with? Commented Jan 9, 2014 at 20:53
  • 1
    First go to json.org and spend ten minutes (that all it takes) to learn the JSON syntax. Commented Jan 9, 2014 at 20:55

3 Answers 3

9

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);
Sign up to request clarification or add additional context in comments.

4 Comments

No i just need to put all data in to hashmap. not a list of hashmap in a single hashmap
Well, since your JSON isn't a hashmap, and your data isn't anything that you could "just put in a hashmap" ... your question makes absolutely no sense then.
when i try to get it in a country class array all field are null Type listType = new TypeToken<country[]>() {}.getType(); country[] carray=gson.fromJson(sb.toString(), listType)
"abosultely no sense" is a bit harsh, you can simply put the keys and values in a hashmap. the keys countryId and countryName and the values being the json string or an object. Yeah creating a pojo is nice, but this can be used as a intermediary. stackoverflow.com/a/14944513/106261
2

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.