Converting Java objects to JSON with Jackson Converting Java objects to JSON with Jackson json json

Converting Java objects to JSON with Jackson

To convert your object in JSON with Jackson:

import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();String json = ow.writeValueAsString(object);

I know this is old (and I am new to java), but I ran into the same problem. And the answers were not as clear to me as a newbie... so I thought I would add what I learned.

I used a third-party library to aid in the endeavor: org.codehaus.jacksonAll of the downloads for this can be found here.

For base JSON functionality, you need to add the following jars to your project's libraries:jackson-mapper-aslandjackson-core-asl

Choose the version your project needs. (Typically you can go with the latest stable build).

Once they are imported in to your project's libraries, add the following import lines to your code:

 import org.codehaus.jackson.JsonGenerationException; import; import com.fasterxml.jackson.databind.ObjectMapper;

With the java object defined and assigned values that you wish to convert to JSON and return as part of a RESTful web service

User u = new User();u.firstName = "Sample";u.lastName = "User"; = "";ObjectMapper mapper = new ObjectMapper();    try {    // convert user object to json string and return it     return mapper.writeValueAsString(u);}catch (JsonGenerationException | JsonMappingException  e) {    // catch various errors    e.printStackTrace();}

The result should looks like this:{"firstName":"Sample","lastName":"User","email":""}

This might be useful:

objectMapper.writeValue(new File("c:\\employee.json"), employee);// display to consoleObject json = objectMapper.readValue(     objectMapper.writeValueAsString(employee), Object.class);System.out.println(objectMapper.writerWithDefaultPrettyPrinter()     .writeValueAsString(json));