0

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?

3
  • 1
    Well, you saw it yourself, the second JSON is not a JSON object. Just parse it as an array instead... Commented Feb 12, 2016 at 22:04
  • @fge If I'm understanding correctly, I did that too, just let me add that to the question. Commented Feb 12, 2016 at 22:07
  • @fge OK, forget what I just said! It does work that way. It was something else that I had overlooked. My bad. Thank you. Commented Feb 12, 2016 at 22:10

1 Answer 1

1

JsonElement is just a superclass of JsonArray and JsonObject.

JsonArray items = root.getAsJsonArray();

should do what you want.

Sign up to request clarification or add additional context in comments.

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.