将org.json.JSONArray插入jackson ObjectNode

时间:2016-04-23 15:34:08

标签: java json jackson

我试图将JSONArray插入杰克逊ObjectNode时遇到困难。这就是我想要做的:

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

感觉真的很傻但实际上最好的办法是什么?!

编辑:我很抱歉因为我没有提到一个重要的观点,即我必须在完成构建后序列化ObjectNode,因此不可能使用putPOJO()

1 个答案:

答案 0 :(得分:3)

我更喜欢aribeiro的方法。您可以使用putPOJO()方法执行此操作。例如:

// 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 here

注意:这是我之前使用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));