David Kroukamp
David Kroukamp

Reputation: 36423

GSON JSON Mapping

Please I need help about to pull my hair out.

Using GSON to read JSON input returned from my PHP web service.

simplified (test) JSON looks like:

{"Posts":[{"post":{"Areaid":"1"}},{"post":{"Areaid":"2"}}]}

Code look like this:

 public void viewAreas() throws Exception {
        List<Map<String, Area>> map=viewAreaResponseToMap("{\"Posts\":[{\"post\":{\"Areaid\":\"1\"}},{\"post\":{\"Areaid\":\"2\"}}]}");

        for (Map<String, Area> map1 : map) {
            for (Map.Entry<String, Area> entry : map1.entrySet()) {
                String string = entry.getKey();
                System.out.println(string);
                Area list = entry.getValue();
                    System.out.println(list.Areaid);
            }
        }
    }

    private List<Map<String, Area>> viewAreaResponseToMap(String response) throws Exception {
        List<Map<String, Area>> map = new Gson().fromJson(response, new TypeToken<List<Map<String, Area>>>() {
        }.getType());

        return map;
    }

with the Area class like:

public class Area {
    public String Areaid;
}

However when I call viewAreas() I get:

java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2

I have tried many different ways i.e Map<String,List<Area>>, List<Map<String,List<Area>>> but I just cant seem to map the JSON response correctly.

Any help or advice?

Upvotes: 0

Views: 158

Answers (1)

herman
herman

Reputation: 12305

It seems like that should be Map<String,List<Map<String,Area>>>, but I've never used GSON before :)

Upvotes: 2

Related Questions