简体   繁体   中英

How to convert a LinkedHashMap<String, List<Node>> into a JSONObject?

I'm new at JSONObject and I'm trying to convert a into a json file. 转换为json文件。 The map is structured in this way:

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

Every Node has two properties: value and label.

What I want is something like this:

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

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

I'm using JSONObject and I looked for a solution in different thread but nothing helped me. I know this is a particolar question, but I need to have this result with this data structure.

The hard point is to loop the nodes element inside the map without overwrite the elements already inserted in the JSONObject.

Thanks.

GSON library will help you to convert object to JSON.

Gson gson = new Gson();
String json = gson.toJson(myMap,LinkedHashMap.class);

Maven Dependency

<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>

You can use stream to convert LinkedHashMap to JsonObject :

Node -class (for example):

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 convert value( List ) => map nodes to builders and collect them use custom collector( Collector.of(...) ) to "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()
                    )
            );
}

Stream of Map.Entry<String, List<Node>> convert each Entry to JsonObject and collect all to 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
                    )
            );

I solved it combining JSONArray and JSONObject class.

I've created the main object using a loop for all the nodes:

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

Then put the jsonArrayOne in a jsonObject:

jsonObjOne.put("items", jsonArrayOne);

And put this jsonObjOne into an jsonArray:

jsonArrayTwo.put(jsonObjOne);

Put this jsonArrayTwo in a jsonObject:

jsonObjTwo.put(element, jsonArrayTwo);

Finally put this jsonObjTwo into the jsonArrayFinal.

jsonArrayFinal.put(jsonObjTwo);

At the end I converted the jsonArrayFinal into a String:

jsonArrayFinal.toString();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM