Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 887
mailme365 Avatar asked Aug 27 '15 02:08

mailme365


2 Answers

Spring boot uses Jackson libraries to convert Java POJO Object to/from Json. These converters are created and used automatically for Rest services to convert POJO object returned by Rest method to Json (e.g. Rest service methods annotated with @ResponseBody). If Rest services are used then Spring creates POJO/Json converters automatically. If you want to make POJO/Json conversion in some different case you need com.fasterxml.jackson.databind.ObjectMapper.

Avoid creating ObjectMapper instance by operator new, reuse the ObjectMapper already available in Spring application context using dependency injection annotation @Autowired. Spring will automatically inject value to your objectMapper variable.

public class clA {
    @Autowired
    private ObjectMapper objectMapper;

    public Optional<String> objToJson(MyObj obj) {

            try {
                String objJackson = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj));
            } catch (JsonProcessingException e) {
                log.debug("failed conversion: Pfra object to Json", e);
            }
        });
}
like image 104
st100 Avatar answered Nov 14 '22 12:11

st100


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;
    }
}
like image 5
brolanda Avatar answered Nov 14 '22 13:11

brolanda