0

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.

Eric Hung
  • 512
  • 8
  • 23

1 Answers1

3

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();
Leo Aso
  • 11,898
  • 3
  • 25
  • 46
  • How about returning `this` by adding `value = a` and `value = o` after a and o are assigned respectively? – Eric Hung Jan 07 '19 at 04:04