Convert Jackson object to JSONObject java

I'm trying to figure out how to convert a Jackson object to a JSONObject?

What I tried, however, I do not believe that this is the right approach.

public JSONObject toJSON() throws IOException { ObjectMapper mapper = new ObjectMapper(); return new JSONObject(mapper.writeValueAsString(new Warnings(warnings))); } 
+6
source share
2 answers

Right now, you serialize your Pojo to String and then parse its String and convert it to a HashMap style object as a JSONObject .

It is very inefficient and brings nothing.

Jackson already provides an ObjectNode class to interact with your Pojo as a JSON object. So just convert your object to ObjectNode . Here is 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 do this is fine.

+4
source

The way you do this works fine, because I also use this method to create a JSON object.

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 here is a sample code for this

 JsonNode jsonNode=mapper.valueToTree(accountInquiryRequestVO); 

It is very easy to use.

+3
source

All Articles