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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With