Search code examples
jsonrx-java2vert.xvertx-verticle

Accessing array elements in a vertx JsonObject


Given the following io.vertx.core.json.JsonObject:

{
"111":[
 {
   "A":"a1",
 },
 {
   "A":"a2",
 },
 {
   "A":"a3",
 }
],
"222":[
 {
   "A":"a10",
 },
 {
   "A":"a20",
 },
 {
   "A":"a30",
 }
]
}
  1. As the name of the outer elements which contain arrays (111 and 222) are not known in advance, what is the correct way to access the elements of each array, e.g.

    {"A":"a1"}

  2. Once the elements of the array are available as a collection, how can that collection be turned into an rxJava Observable. Have tried the following:

    List list = arrayElements.stream().collect(Collectors.toList());

    Observable observable = Observable.fromIterable(list);

However, the issue is that each element in the stream is then represented as a java.util.LinkedHashMap.Entry, e.g. A=a1, whereas what is required is to retain the original Json representation.

Thanks


Solution

  • You can get object fields with JsonObject.fieldNames().

    JsonArray is an Iterable<Object> because it may contain different types (objects, strings, ...etc). If you are confident that a JsonArray only contains JsonObject, you could cast the value.

    Here's the result combined:

    for (String fieldName : jsonObject.fieldNames()) {
        JsonArray jsonArray = jsonObject.getJsonArray(fieldName);
        Observable<JsonObject> observable = Observable
                .fromIterable(jsonArray)
                .map(JsonObject.class::cast);
        System.out.println("fieldName = " + fieldName);
        observable.subscribe(json -> System.out.println("json = " + json));
    }