3 回答

TA貢獻1946條經驗 獲得超4個贊
我結合 JSONArray 和 JSONObject 類解決了它。
我使用循環為所有節點創建了主對象:
for (Node node : nodeList){ try { JSONObject obj = new JSONObject(); obj.put("value", node.getValue()); obj.put("label", node.getLabel()); jsonArrayOne.put(obj) } catch (JSONException e) { log.info("JSONException"); }}
然后將 jsonArrayOne 放入一個 jsonObject 中:
jsonObjOne.put("items", jsonArrayOne);
并將這個 jsonObjOne 放入一個 jsonArray 中:
jsonArrayTwo.put(jsonObjOne);
把這個 jsonArrayTwo 放在一個 jsonObject 中:
jsonObjTwo.put(element, jsonArrayTwo);
最后把這個jsonObjTwo放到jsonArrayFinal中。
jsonArrayFinal.put(jsonObjTwo);
最后,我將 jsonArrayFinal 轉換為字符串:
jsonArrayFinal.toString();

TA貢獻1829條經驗 獲得超7個贊
您可以使用stream轉換LinkedHashMap為JsonObject:
Node-類(例如):
public class Node {
private final String value;
private final String label;
private Node(String value, String label) {
this.value = value;
this.label = label;
}
//Getters
}
toItems-方法轉換值(列表)=> 將節點映射到構建器并使用自定義收集器(Collector.of(...))將它們收集到“項目” JsonObject:
static JsonObject toItems(List<Node> nodes) {
return nodes
.stream()
.map(node ->
Json.createObjectBuilder()
.add("value", node.getValue())
.add("label", node.getLabel())
).collect(
Collector.of(
Json::createArrayBuilder,
JsonArrayBuilder::add,
JsonArrayBuilder::addAll,
jsonArrayBuilder ->
Json.createObjectBuilder()
.add("items", jsonArrayBuilder)
.build()
)
);
}
Stream將Map.Entry<String, List<Node>>每個轉換Entry為JsonObject并收集所有到Root -object:
Map<String, List<Node>> nodes = ...
JsonObject jo = nodes
.entrySet()
.stream()
.map((e) -> Json.createObjectBuilder().add(e.getKey(), toItems(e.getValue()))
).collect(
Collector.of(
Json::createObjectBuilder,
JsonObjectBuilder::addAll,
JsonObjectBuilder::addAll,
JsonObjectBuilder::build
)
);

TA貢獻1786條經驗 獲得超11個贊
GSON 庫將幫助您將對象轉換為 JSON。
Gson gson = new Gson();
String json = gson.toJson(myMap,LinkedHashMap.class);
Maven 依賴
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
添加回答
舉報