I'm trying to figure out how to convert a Jackson object into a JSONObject?
What I've tried, however I don't believe this is the correct approach.
public JSONObject toJSON() throws IOException {
ObjectMapper mapper = new ObjectMapper();
return new JSONObject(mapper.writeValueAsString(new Warnings(warnings)));
}
The way you are doing is work fine, because i also use that way to make a JSONobject.
here is my code
public JSONObject getRequestJson(AccountInquiryRequestVO accountInquiryRequestVO) throws JsonGenerationException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();
JSONObject jsonAccountInquiry;
jsonAccountInquiry=new JSONObject(mapper.writeValueAsString(accountInquiryRequestVO));
return jsonAccountInquiry;
}
its working fine for me. but you can always use JsonNode also here is the sample code for that
JsonNode jsonNode=mapper.valueToTree(accountInquiryRequestVO);
its very easy to use.
Right now, you are serializing your Pojo to a String
, then parsing that String
and converting it into a HashMap
style object in the form of JSONObject
.
This is very inefficient and doesn't accomplish anything of benefit.
Jackson already provides an ObjectNode
class for interacting with your Pojo as a JSON object. So just convert your object to an ObjectNode
. Here's a working example
public class Example {
public static void main(String[] args) throws Exception {
Pojo pojo = new Pojo();
pojo.setAge(42);
pojo.setName("Sotirios");
ObjectMapper mapper = new ObjectMapper();
ObjectNode node = mapper.valueToTree(pojo);
System.out.println(node);
}
}
class Pojo {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Otherwise, the way you are doing it is fine.
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