【问题标题】:Get keys from nested JSONObject fluently流畅地从嵌套的 JSONObject 中获取密钥
【发布时间】:2019-01-04 10:30:08
【问题描述】:

我正在尝试从嵌套的 JSONObject 中提取一个值,例如“id”。我正在使用org.json.simple 包,我的代码如下所示:

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

其中 response 是一个 JSONObject。

是否可以使用 Fluent Interface Pattern 重构代码,使代码更具可读性?例如,

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

提前致谢。

【问题讨论】:

    标签: java fluent-interface


    【解决方案1】:

    这是一种可能性。

    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;
        }
    }
    

    你可以这样使用它

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

    【讨论】:

    • 在a和o分别赋值后加上value = avalue = o返回this怎么样?
    猜你喜欢
    • 2018-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-08
    • 2023-01-23
    • 2021-07-26
    • 1970-01-01
    • 2011-03-09
    相关资源
    最近更新 更多