kimi1990mp
kimi1990mp

Reputation: 141

Create JSON object from List in Java

I have a List<String> where each element represents a node and a String which is the value that corresponds to the last node of that list. The list represents the path to the value. So, basically each element of the list is the value of the previous element. I would like to create a JSON object from it using Jackson. However, this needs to be done dynamically, not explicitly setting the nodes of the JSON object, because the list will not always be the same.

So, I am wondering if there is a way to convert or iterate through the list and create the JSON object. So, if my list looks like this:

["user", "car", "brand"] and the value is "BMW", the JSON object should look like this:

{
   "user":
      {
        "car":
          {
            "brand": "BMW"
          }
      }
}

Upvotes: 0

Views: 4224

Answers (2)

dzimney
dzimney

Reputation: 552

Iterate through the list in reverse and upon each iteration create a new JsonNode for the list element, add the previous JsonNode as a child to the new JsonNode and overwrite the original reference with the new JsonNode. Rinse and repeat.

Something like...

final String value = "BMW"; // whatever the final "value" is.
final ObjectMapper objectMapper = new ObjectMapper();

ObjectNode json = null;

for (int i = list.size() - 1; i >= 0; i--) {

  final String prop = list.get(i);
  final ObjectNode objectNode = objectMapper.createObjectNode();

  if (json == null) {
    objectNode.put(prop, value);
  } else {
    objectNode.put(prop, json);
  }

  json = objectNode;
}

Upvotes: 2

Vishal Varshney
Vishal Varshney

Reputation: 103

Here is the piece of code which you need

package uk.co.vishal;

import com.fasterxml.jackson.core.JsonProcessingException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Answer {

public static void main(String[] args) throws JsonProcessingException {
    List<String> data = new ArrayList<>();
    data.add("user");
    data.add("car");
    data.add("brand");

    System.out.println(data.toString());

    Map<String, String> mydata = new HashMap<>();
    Map<String, JSONObject> newdata = new HashMap<>();
    JSONObject result = new JSONObject();
    boolean flag = true;

    for (int i = data.size() - 1; i >= 0; i--) {
        if (flag) {
            mydata.put(data.get(i), "BMW");
            result = generateJson(mydata);
            flag = false;
        } else {
            newdata.put(data.get(i), result);
            result = generateJson(newdata);
            newdata.clear();
        }
    }
    System.out.println(result);
    /*
    * Here is the output:
    * {
        "user": {
            "car": {
                    "brand": "BMW"
                }
            }
      }
    *
    * */
}

private static JSONObject generateJson(Map data) {
    return new JSONObject(data);
}

}

I hope you will be sorted !!

Upvotes: -1

Related Questions