11

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.

mailme365
  • 511
  • 2
  • 9
  • 20

5 Answers5

10

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);
            }
        });
}
st100
  • 415
  • 4
  • 10
5

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;
    }
}
kryger
  • 12,906
  • 8
  • 44
  • 65
brolanda
  • 63
  • 6
  • 2
    I figured out that spring is using com.fasterxml.jackson, that's why the maven library is different. and the newest library does have a convenient way to convert POJO to JSON String directly : String jsonString = mapper.writeValueAsString(myResultObject); – mailme365 Aug 27 '15 at 03:17
  • Since it's been a while, is it still the best way to do this ? – Paul Mar 06 '17 at 12:27
0
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public static String jsonToPojo(Object targetPojo) {

    if(targetPojo == null)
        return null;
    ObjectMapper mapper = new ObjectMapper();

    try {
         mapper.enable(SerializationFeature.INDENT_OUTPUT);
         return mapper.writeValueAsString(targetPojo);

    } catch (IOException e) {
        LOGGER.error("Error parsing string to json. Target pojo : {}", targetPojo.getClass().getName() );
    }
     return null;
}
Saju
  • 402
  • 3
  • 11
  • 30
-1

You should add the code like this in your pom.xml file

    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-core-asl</artifactId>
        <version>1.9.13</version>
    </dependency>
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.9.13</version>
    </dependency>

then you could return object at your contorller like this

@ResponseBody
public TheClassYouDefine method(){

  return object;
}

jackson will convert object to json

brolanda
  • 63
  • 6
  • My conversion requirement is not for restful web service, I want to convert POJO to JSON and save json to database, @ResponseBody is not suitable for my case. I wonder if Spring internally rely on Jackson to do the conversoin, why the jackson-apper-asl is not included in maven dependency hierachy? And what's the best way to do the conversion in a Spring project (without using @ResponseBody) – mailme365 Aug 27 '15 at 02:37
-3

To answer your questions: 1.spring restful couldn't convert pojo to json,it use jackson to do this,and you must add the two lib like the the answer above. 2.you don't need to write json to any file ,you could get json string in your page ,and you could use ajax request to get them .Then you could use jquery to put them at anywhere in your page. 3.I don't know the spring have the mechanism to convert pojo to json in B/S application.So if you could tell me how to do it ,it's very thanksful

brolanda
  • 63
  • 6