Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Jackson object into JSONObject java

Tags:

java

json

jackson

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)));
}
like image 392
Code Junkie Avatar asked Mar 07 '14 19:03

Code Junkie


2 Answers

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.

like image 108
MadukaJ Avatar answered Nov 18 '22 23:11

MadukaJ


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.

like image 25
Sotirios Delimanolis Avatar answered Nov 19 '22 00:11

Sotirios Delimanolis