Matteo Zaccagnino
Matteo Zaccagnino

Reputation: 23

Insert org.json.JSONArray into jackson ObjectNode

I have got stuck trying to insert a JSONArray into a Jackson ObjectNode. This is what I am trying to do:

public void myMethod(JSONArray jsonArray) {
    ObjectNode payload = objectMapper.createObjectNode(0);
    payload.put("array", /* jsonArray */);
    payload.put(/* some other things */);
    ...
}

It feels like something really silly but what is actually the best way to do it?!

EDIT: I am sorry beacause I did not mention an important point, that is I have to serialize the ObjectNode once I finished building it, so using putPOJO() is not a possibility.

Upvotes: 1

Views: 6321

Answers (1)

ck1
ck1

Reputation: 5443

I like aribeiro's approach more. You can use the putPOJO() method to do this. For example:

// Incoming org.json.JSONArray.
JSONArray incomingArray = new JSONArray("[\"Value1\",\"Value2\"]");

ObjectMapper objectMapper = new ObjectMapper();
ObjectNode payload = objectMapper.createObjectNode();
// Adds the JSONArray node to the payload as POJO (plain old Java object).
payload.putPOJO("array", incomingArray);

System.out.println(objectMapper.writeValueAsString(payload));

Javadoc can be found here.

Note: here's a previous implementation that I submitted using readTree():

// Incoming org.json.JSONArray.
JSONArray incomingArray = new JSONArray("[\"Value1\",\"Value2\"]");

ObjectMapper objectMapper = new ObjectMapper();
ObjectNode payload = objectMapper.createObjectNode();
// Reads the JSON array into a Jackson JsonNode.
JsonNode jsonNode = objectMapper.readTree(incomingArray.toString());
// Sets the Jackson node on the payload.
payload.set("array", jsonNode);

System.out.println(objectMapper.writeValueAsString(payload));

Upvotes: 4

Related Questions