简体   繁体   中英

Parsing jsonobject when entire json is an array?

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;

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

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

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");
            }

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

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

And setting

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

to

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

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

JsonElement is just a superclass of JsonArray and JsonObject.

JsonArray items = root.getAsJsonArray();

should do what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM