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>
添加回答
举报
