kasavbere kasavbere - 6 months ago 68
Java Question

From org.json JSONObject to org.codehaus.jackson

I want to move from org.json to org.codehaus.jackson. How do I convert the following java code?

private JSONObject myJsonMessage(String message){
JSONObject obj = new JSONObject();
obj.put("message",message);
return obj;
}


I leave out the try-catch for simplicity.

Answer

Instead of JSONObject use Jackson's ObjectMapper and ObjectNode:

ObjectMapper mapper = new ObjectMapper();
ObjectNode node = mapper.createObjectNode();
node.put("message", "text");

This would be Jackson's equivalent of your current org.json code.

However, where Jackson really excels is in its capacity to do complex mappings between your Java classes (POJOs) and their JSON representation, as well as its streaming API which allows you to do really fast serialization, at least when compared with org.json's counterparts.