What's the best way to convert pojo to JSON in Spring

mailme365 picture mailme365 · Aug 27, 2015 · Viewed 17.9k times · Source

I have a requirement to convert a POJO to JSON string in a Spring project. I know Spring MVC provide a convenient way to return json in the controller by annotate @ResponseBody, I wonder how does Spring convert pojo to JSON internally? From the Spring MVC maven dependencies hierachy, I find jackson-databind and jackson-core library. While reading the Jackson tutorial, it says different library:

<dependencies>
  <dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.8.5</version>
  </dependency>
</dependencies>

And the convert code is similar as below:

ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(new File("c:\\user.json"), user);

My questions are:

1: How does spring restful controller convert POJO to JSON? By using Jackson but different dependency library?

2: If I use above Jackson example to convert POJO to JSON, do I have to write the json to file? Is it possible to get the JSON string directly?

3: What's the best way to convert POJO to JSON in Spring project -- Without using @ResponseBody, since I want to convert POJO to JSON and save it to database, @ResponseBody is for restful service, not suitable for my case.

Thanks a lot for your answers in advance.

Answer

brolanda picture brolanda · Aug 27, 2015

If you don't want to use Spring MVC to convert object to JSON string, you could do it like this:

private JsonGenerator jsonGenerator = null;
private ObjectMapper objectMapper = null;
public void init(){
  objectMapper = new ObjectMapper();
  try{
     jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(System.out, JsonEncoding.UTF8);
     jsonGenerator.writeObject(bean); 
     objectMapper.writeValue(System.out, bean);
  }catch (IOException e) {
        e.printStackTrace();
  }
  jsonGenerator.flush();
  jsonGenerator.close();
}

You must declare the bean like this

public class AccountBean {
    private int id;
    private String name;
    private String email;
    private String address;
    private Birthday birthday;

    //getters, setters

    @Override
    public String toString() {
        return this.name + "#" + this.id + "#" + this.address + "#" + this.birthday + "#" + this.email;
    }
}