How to get the value of a JSON field

Asked

Viewed 48 times

0

I want to get the strings from inside the field text but they end up returning null.

The JSON I get is this:

{"type":"RichMessage","message":{"type":"ChatWindowMenu","name":"Blitz","items":[{"text":"Login"},{"text":"Registro"}],"schedule":{"responseDelayMilliseconds":0.0},"agentId":"0Xx5Y000000g5uPSAQ"}}

Code:

JsonReader reader = Json.createReader(con.getInputStream());
JsonObject mresObj = reader.readObject();
JsonArray items = mresObj.getJsonArray("text");
for (int i = 0; i < items.size(); i++) {
    JsonObject arrayItems = items.getJsonObject(i);
    System.out.println("items->"+arrayItems.toString());
}

1 answer

3

You are accessing the JSON file as if it had another structure. View JSON content in a more structured and easy-to-understand way:

{
  "type": "RichMessage",
  "message": {
    "type": "ChatWindowMenu",
    "name": "Blitz",
    "items": [
      {
        "text": "Login"
      },
      {
        "text": "Registro"
      }
    ],
    "schedule": {
      "responseDelayMilliseconds": 0
    },
    "agentId": "0Xx5Y000000g5uPSAQ"
  }
}

In your code, you’ll need:

  1. Get the JSON root object
  2. Take his "message" field, which is another object
  3. Take his "items" field, which is another object
  4. Iterate in this "items" field and pick up each child element, which is an object
  5. Take his "text" field, which is a text

Therefore, a suggested code would be:

JsonReader reader = Json.createReader(con.getInputStream());
JsonObject mresObj = reader.readObject();
JsonObject message = mresObj.getJsonObject("message");
JsonArray items = message.getJsonArray("items");
for (JsonValue value : items) {
    JsonObject itemChild = value.asJsonObject();
    String text = itemChild.getString("text");
    System.out.println(text);
}

I suggest using simpler JSON reading libraries, for example Gson.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.