17

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)));
}
0

2 Answers 2

15

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.

Sign up to request clarification or add additional context in comments.

Comments

10

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.