Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

From org.json JSONObject to org.codehaus.jackson

Tags:

java

json

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 left out the try-catch block for simplicity.

like image 797
kasavbere Avatar asked Sep 21 '12 23:09

kasavbere


People also ask

How do you serialize an object to JSON Jackson in Java?

Converting Java object to JSON In it, create an object of the POJO class, set required values to it using the setter methods. Instantiate the ObjectMapper class. Invoke the writeValueAsString() method by passing the above created POJO object. Retrieve and print the obtained JSON.

How do you mark a class as ignorable Jackson?

Alternatively, you can also use @JsonIgnoreProperties annotation to ignore undeclared properties. The @JsonIgnoreProperties is a class-level annotation in Jackson and it will ignore every property you haven't defined in your POJO.


1 Answers

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.

like image 98
João Silva Avatar answered Oct 18 '22 22:10

João Silva