-2

I am having a JSON Array which I am populating using a JSON object, and the code looks like this

    Map<String, String> orderLines = new HashMap<>();
    orderLines.put("xx",XX);
    orderLines.put("yy",YY);
JSONObject obj=new JSONObject(orderLines);
JSONArray array = new JSONArray().put(obj);

and I am trying to add this array into my map and add it to the

Map<String, Object> customFields = new HashMap<>();
customFields.put("postOrderRequest.orderLines", array);

but when I am building a json out of these map values using

customFields.forEach((k, v) -> json.set(k, v));

, I am not able to build a json out of the map,what I am trying to achieve is something like this

{
    "orderLines" : [{"xx":"XX","yy":"YY"}]
 }
Dhirish
  • 31
  • 1
  • 1
  • 9

1 Answers1

0

You can try this (without any external library - using only Java 8)

    Map<String, Object> customFields = new LinkedHashMap<>();

    List<String> jsonKeyList = List.of("orderLines1", "orderLines2");
    jsonKeyList.forEach(listItem -> orderKeys(listItem, customFields));

    String result = "{" + customFields.entrySet().stream()
                                      .map(e -> "\"" + e.getKey() + "\":" +
                                                String.valueOf(e.getValue()))
                                      .collect(Collectors.joining(", ")) +
                    "}";

    System.out.println("Result: " + result);
}

public static void orderKeys(final String key, final Map<String, Object> result)
{
    JSONArray array = new JSONArray();
    JSONObject item = new JSONObject();
    item.put("xx", "XX");
    item.put("yy", "YY");
    array.put(item);

    result.put(key, array);
}

Output:

Result: {"orderLines1":[{"xx":"XX","yy":"YY"}], "orderLines2":[{"xx":"XX","yy":"YY"}]}

Else you can use external libraries for your usecase (viz. Underscore-java - library to convert hash map or array list to json and vice versa).

Courtesy: StackOverflow

VikramV
  • 1,111
  • 2
  • 13
  • 31