简体   繁体   中英

Get keys from nested JSONObject fluently

I'm trying to extract a value from a nested JSONObject, say "id". I'm using org.json.simple package and my code looks like:

JSONArray entries = (JSONArray) response.get("entries");
JSONObject entry = (JSONObject) entries.get(0);
JSONArray runs = (JSONArray) entry.get("runs");
JSONObject run = (JSONObject) runs.get(0);
String run_id = run.get("id").toString();

where response is a JSONObject.

Is it possible to refactor the code using Fluent Interface Pattern so the code is more readable? For example,

String run_id = response.get("entries")
        .get(0)
        .get("runs")
        .get(0)
        .get("id").toString();

Thanks in advance.

Here's a possibility.

class FluentJson {
    private Object value;

    public FluentJson(Object value) {
        this.value = value;
    }

    public FluentJson get(int index) throws JSONException {
        JSONArray a = (JSONArray) value;
        return new FluentJson(a.get(index));
    }

    public FluentJson get(String key) throws JSONException {
        JSONObject o = (JSONObject) value;
        return new FluentJson(o.get(key));
    }

    public String toString() {
        return value == null ? null : value.toString();
    }

    public Number toNumber() {
        return (Number) value;
    }
}

You can use it like this

String run_id = new FluentJson(response)
    .get("entries")
    .get(0)
    .get("runs")
    .get(0)
    .get("id").toString();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM