Parsing jsonobject when entire json is an array?

时间:2016-02-12 22:02:51

标签: java json parsing gson

I am using gson-2.5 for this. There is a slight difference in the format of these two jsons, where in the first one;

Call to a member function add_section() on a non-object in functions.php line 5

I would have parsed this to get "text" this way, and everything would be ok;

"usethis": [
    {
      "id": 111,
      "text": "some text that i would like",
    },
  {
      "id": 222,
      "text": "someothertextiwouldlike",
    }
]

The difference is that in the second one, I have nothing to get as the rootobject unlike in the first where I used "usethis";

JsonParser jp = new JsonParser();
        JsonElement root = jp.parse(listcontents);
        JsonObject rootobj = root.getAsJsonObject();

        JsonArray items = rootobj.get("usethis").getAsJsonArray();
        for(int i = 0; i < items.size(); i++) {
            JsonObject item = items.get(i).getAsJsonObject();
            String thetext = item.get("text").getAsString();
            System.out.println("text: " + thetext  + "\n");
            }

And setting

[
  {
      "id": 111,
      "text": "some text that i would like",
    },
  {
      "id": 222,
      "text": "someothertextiwouldlike",
    }
]

to

rootobj.get("usethis").getAsJsonArray();

just gives me an error. How would I be able to parse the second json?

1 个答案:

答案 0 :(得分:1)

JsonElement只是JsonArray和JsonObject的超类。

JsonArray items = root.getAsJsonArray();

应该做你想做的事。