Search code examples
javafluent-interface

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.


Solution

  • 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();