Converting Java objects to JSON with Jackson

I want my JSON to look like this:

{
    "information": [{
        "timestamp": "xxxx",
        "feature": "xxxx",
        "ean": 1234,
        "data": "xxxx"
    }, {
        "timestamp": "yyy",
        "feature": "yyy",
        "ean": 12345,
        "data": "yyy"
    }]
}

Code so far:

import java.util.List;

public class ValueData {

    private List<ValueItems> information;

    public ValueData(){

    }

    public List<ValueItems> getInformation() {
        return information;
    }

    public void setInformation(List<ValueItems> information) {
        this.information = information;
    }

    @Override
    public String toString() {
        return String.format("{information:%s}", information);
    }

}

and

public class ValueItems {

    private String timestamp;
    private String feature;
    private int ean;
    private String data;


    public ValueItems(){

    }

    public ValueItems(String timestamp, String feature, int ean, String data){
        this.timestamp = timestamp;
        this.feature = feature;
        this.ean = ean;
        this.data = data;
    }

    public String getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(String timestamp) {
        this.timestamp = timestamp;
    }

    public String getFeature() {
        return feature;
    }

    public void setFeature(String feature) {
        this.feature = feature;
    }

    public int getEan() {
        return ean;
    }

    public void setEan(int ean) {
        this.ean = ean;
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return String.format("{timestamp:%s,feature:%s,ean:%s,data:%s}", timestamp, feature, ean, data);
    }
}

I just missing the part how I can convert the Java object to JSON with Jackson:

public static void main(String[] args) {
   // CONVERT THE JAVA OBJECT TO JSON HERE
    System.out.println(json);
}

My Question is: Are my classes correct? Which instance do I have to call and how that I can achieve this JSON output?


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.jackson All 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-asl and jackson-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 org.codehaus.jackson.map.JsonMappingException;
 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";
u.email = "[email protected]";

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":"[email protected]"}


This might be useful:

objectMapper.writeValue(new File("c:\\employee.json"), employee);

// display to console
Object json = objectMapper.readValue(
     objectMapper.writeValueAsString(employee), Object.class);

System.out.println(objectMapper.writerWithDefaultPrettyPrinter()
     .writeValueAsString(json));

Just follow any of these:

  • For jackson it should work:

          ObjectMapper mapper = new ObjectMapper();  
          return mapper.writeValueAsString(object);
          //will return json in string
    
  • For gson it should work:

        Gson gson = new Gson();
        return Response.ok(gson.toJson(yourClass)).build();