io.nitor.api.backend.util.JsonPointer.java Source code

Java tutorial

Introduction

Here is the source code for io.nitor.api.backend.util.JsonPointer.java

Source

/**
 * Copyright 2018 Nitor Creations Oy
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.nitor.api.backend.util;

import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;

public class JsonPointer {
    public static String fetch(JsonObject root, String pointer) {
        if (pointer.length() == 0) {
            return null;
        }
        int arrIdx = pointer.indexOf("[]");
        int dotIdx = pointer.indexOf('.');
        if (dotIdx == 0) {
            pointer = pointer.substring(1);
            arrIdx = pointer.indexOf("[]");
            dotIdx = pointer.indexOf('.');
        }
        if (arrIdx > 0 && arrIdx < dotIdx) {
            Object val = root.getValue(pointer.substring(0, arrIdx));
            if (val instanceof JsonArray) {
                StringBuffer sb = new StringBuffer();
                String remaining = pointer.substring(arrIdx + 2);
                ((JsonArray) val).forEach(o -> {
                    String value;
                    if (o instanceof JsonObject) {
                        value = fetch((JsonObject) o, remaining);
                    } else {
                        value = o.toString();
                    }
                    if (value != null) {
                        sb.append(value).append(',');
                    }
                });
                if (sb.length() > 0) {
                    sb.setLength(sb.length() - 1);
                }
                return sb.toString();
            }
            return null;
        }
        String key = dotIdx < 0 ? pointer : pointer.substring(0, dotIdx);
        Object val = root.getValue(key);
        if (val instanceof JsonObject) {
            return fetch((JsonObject) val, pointer.substring(dotIdx + 1));
        }
        if (val == null) {
            return null;
        }
        return val.toString();
    }
}