0

I would like to iterate over an array in this Json object:

{
  "id": "2234",
  "Messages": [
    {
      "MessageId": 321231239,
      "Text_message": "my text message",
      "date": 1444666348
    },
    {
      "MessageId": 3217437239,
      "Text_message": "my text message 2",
      "date": 1444666348
    }
  ]
}

in my code I have:

JsonArray messagesJson = jsonObject.getJsonArray("Messages");

my imports related to this are:

import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonObject;
import javax.json.JsonReader;

Now I want to iterate over this array and extract fields for my bean. But I don't want to use the for loop with index. I want to use a foreach type of loop. I am working with Java 7. What I want is something that is more like the Scala way of doing it:

messagesJson.map { json => 
    MyBean(
        (json \ "MessageId").getOrElse(""),
        (json \ "text_message").getOrElse(""),
        (json \ "date").getOrElse("")
    )
}
2
  • 1
    use Gson o jackson, they simplify the iteration and are developed to make easier the life Commented Feb 2, 2016 at 18:37
  • 1
    What's wrong with for ( JsonValue val : messageJson ) ...? Commented Feb 2, 2016 at 18:37

1 Answer 1

2

As the documentation says, JsonArray extends List<JsonValue> so you can simply iterate over JsonValue.

for(JsonValue value : yourJsonArray){
....
}
Sign up to request clarification or add additional context in comments.

2 Comments

How would you turn value into JsonObject?
you can use getValueType() and check if the result is equal to one of the values of JsonType.ValueType enum. Take a look here: docs.oracle.com/javaee/7/api/javax/json/…

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.