如何转换LinkedHashMap >进入JSONObject?

问题描述 投票:2回答:4

我是JSONObject的新手,我正在尝试将LinkedHashMap <String,List <Node >>转换为json文件。地图以这种方式构建:

"element_one", {Node1, Node2, etc...}
"element_two", {Node1, Node2, etc...}

每个节点都有两个属性:值和标签。

我想要的是这样的:

{
"element_one": [
{
"items": [
  {
    "value": "1",
    "label": "Donald"
  },
  {
    "value": "2",
    "label": "Goofy"
  }]
}],

"element_two": [
{
"items": [
  {
    "value": "1",
    "label": "Peter"
  },
  {
    "value": "2",
    "label": "Wendy"
  }]
}}

我正在使用JSONObject,我在不同的线程中寻找解决方案,但没有任何帮助我。我知道这是一个特别的问题,但我需要在这个数据结构中得到这个结果。

难点是在地图内循环节点元素而不覆盖已插入JSONObject中的元素。

谢谢。

java json linkedhashmap jsonconvert
4个回答
0
投票

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>

0
投票

你可以使用streamLinkedHashMap转换成JsonObject

Node-class(例如):

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-method转换值(List)=>将节点映射到构建器并使用自定义收集器(Collector.of(...))将它们收集到“items”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()
                    )
            );
}

StreamMap.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
                    )
            );

0
投票

我结合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转换为String:

jsonArrayFinal.toString();

-1
投票

这是一个有效的实现:

import jettison.json.JSONArray;
import jettison.json.JSONException;
import jettison.json.JSONObject;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

class Node {
    private final String value;
    private final String name;

    public Node(String value, String name) {
        this.value = value;
        this.name = name;
    }

    String getValue() {
        return this.value;
    }
    String getName() {
        return this.name;
    }
}

public class Main {

    public static void main(String[] args) {
        LinkedHashMap<String, List<Node>> mMap = new LinkedHashMap<>();

        List<Node> mList1 = new ArrayList<>();
        List<Node> mList2 = new ArrayList<>();

        // Create a Node list.
        mList1.add(new Node("1", "Donald"));
        mList1.add(new Node("2", "Goofy"));

        // Create another Node list.
        mList2.add(new Node("1", "Peter"));
        mList2.add(new Node("2", "Wendy"));

        // We finalize our map here.
        mMap.put("element_one", mList1);
        mMap.put("element_two", mList2);


        JSONObject jObject = new JSONObject();
        JSONArray jArray;
        try
        {
            for(String key : mMap.keySet()) {
                JSONObject jObjectItems = new JSONObject();
                jArray = new JSONArray();
                for (Node node : mMap.get(key)) {
                    JSONObject NodeJSON = new JSONObject();
                    NodeJSON.put("name", node.getName());
                    NodeJSON.put("value", node.getValue());
                    jArray.put(NodeJSON);
                }
                jObjectItems.put("items: ", jArray);
                jObject.put(key,jObjectItems);
            }
        } catch (JSONException jse) {
            System.out.println("JSONException!");
        }

        String result = jObject.toString();
        System.out.println(result);
    }
}

如果你运行这个程序,它将打印到stdout:

{"element_one":{"items: ":[{"name":"Donald","value":"1"},{"name":"Goofy","value":"2"}]},"element_two":{"items: ":[{"name":"Peter","value":"1"},{"name":"Wendy","value":"2"}]}}

我使用了jettison库:

Jettison Github Page

© www.soinside.com 2019 - 2024. All rights reserved.