簡體   English   中英

(Java)使用Java8將JSONObject的JSONArray展平為[[]]

[英](Java) Flatten JSONArray of JSONObject to [[]] with Java8

我正在使用net.sf.json.JSONArray和net.sf.json.JSONObject。 JSONArray包含多個JSONObject。

基本上是這樣的:

[
    {
        "obj1": [
            {
                "ID": 12
                "NAME":"Whatever",
                "XY":[1,2]
            },
            {
                "ID": 34
                "NAME":"Again",
                "XY":[23,43]
            },
            etc
        ]
    },
    { "obj2": repeat}
]

我想用Java 8將其扁平化,即結果:

[
    {
        "obj1": [
                    [12,'Whatever',1,2],
                    [34,'Again',23,43],
                    etc...
        ]
    },
    { "obj2": repeat}
]

盡管您可以通過強制性方式輕松地完成此操作(不帶遞歸),但以函數樣式實現可能會更容易。 我不確定我是否擅長Java 8中的慣用功能代碼,但您需要:

  • 將項目收集到單個陣列的收集器
static Collector<Object, JSONArray, JSONArray> toJSONArray() {
    return Collector.of(
            JSONArray::new,     // Create a new array
            JSONArray::add,     // Add each element to the target array
            (a1, a2) -> {       // Merge the second array into the first one
                a1.addAll(a2);
                return a1;
            },
            identity()          // Return the populated array itself
    );
}
static Stream<?> flatten(final Object value) {
    return value instanceof Collection
            ? ((Collection<?>) value).stream().flatMap(Q43481457::flatten) // Flatten recursively
            : Stream.of(value);                                            // Otherwise wrap a single element into a stream
}
  • 和主要代碼:
@SupressWarnings("unchecked")
final Collection<JSON> jsonArray = (Collection<JSON>) originalJsonArray;
final JSONArray flatJSONArray = jsonArray.stream()
        .map(json -> (Map<?, ?>) json)          // All outer array elements are JSON objects and maps in particular
        .map(jsonObject -> jsonObject.values()  // Recursively flatten the JSON object values
                .stream()
                .flatMap(Q43481457::flatten)
                .collect(toJSONArray())         // ... collecting them to JSON arrays
        )
        .collect(toJSONArray());                // ... which are collected to JSON arrays
System.out.println(flatJSONArray);

輸出:

[12, “不管”,1,2],[34, “再”,23,43]]

用法

JSONArray array = ...;
JSONArray flattedArray = flatten(array);

JSONObject map = ...;
JSONObject flattedMap = flatten(map);

履行

當json結構更改時,實現發生了巨大的變化,您可以在github上比較我的提交歷史記錄。 測試可以告訴您我如何實現您的功能。

public JSONArray flatten(Collection<?> array) {
    return array.stream().flatMap(this::flatting).collect(toJSONArray());
}

private Stream<?> flatting(Object it) {
    if (it instanceof Collection) {
        return ((Collection<?>) it).stream();
    }
    if (it instanceof Map) {
        return Stream.of(flatten((Map<?, ?>) it));
    }
    return Stream.of(it);
}

public JSONObject flatten(Map<?, ?> map) {
    return map.entrySet().stream().collect(
            JSONObject::new,
            (it, field) -> it.put(field.getKey(), flatten(field.getValue())),
            JSONObject::putAll
    );
}

private Object flatten(Object it) {
    if (it instanceof Collection) {
        return ((Collection<?>) it).stream().map(this::flatten)
                                            .collect(toJSONArray());
    }
    if (it instanceof Map) {
        return flatten(((Map<?, ?>) it).values());
    }
    return it;
}

private <T> Collector<T, ?, JSONArray> toJSONArray() {
    return toCollection(JSONArray::new);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM