After build() with JsonObject from JsonObjectBuilder builder will be cleaned up to be ready for reuse. To illustrate this:
JsonObjectBuilder b = Json.createObjectBuilder(); b.add("foo", "bar"); JsonObject o = b.build(); JsonObject p = b.build(); System.out.println(o.toString()); // {"foo":"bar"} System.out.println(p.toString()); // {}
When you do
l1.add(l.getValue());
build() is called implicitly on one , so it will be empty.
Then here:
System.out.println("JSON2: " + HASH_MAP.get("one").build().toString());
you are creating a view of an empty JsonObject .
To perform a migration, you can, for example, store JsonObjects instead of JsonObjectBuilders in your hash file:
Map<String, JsonObject> HASH_MAP = new HashMap<>(); JsonObjectBuilder one = Json.createObjectBuilder(); one.add("test1","test1"); HASH_MAP.put("one", one.build()); JsonObjectBuilder two = Json.createObjectBuilder(); two.add("test2","test2"); HASH_MAP.put("two", two.build()); JsonObjectBuilder toReturn = Json.createObjectBuilder(); JsonArrayBuilder l1 = Json.createArrayBuilder(); for (Map.Entry<String, JsonObject> l : HASH_MAP.entrySet()) { l1.add(l.getValue()); } toReturn.add("l1", l1); toReturn.add("otherParam", "value2"); String strJSON = toReturn.build().toString(); System.out.println("JSON1: " + strJSON); System.out.println("JSON2: " + HASH_MAP.get("one").toString());
Now it should work as you expect.
source share