Today: October 12, 2024 7:39 pm
A collection of Software and Cloud patterns with a focus on the Enterprise

RESTful Java Servlet: Serializing to/from JSON with Jackson

In a previous article I demonstrated one way to create a RESTful interface using a plain Java Servlet. In this article I wanted to extend that to include JSON serialization using Jackson.

I found a very simple article showing a basic case mapping a POJO to JSON and back again. However, when I copied this straight over I got the following error:

org.codehaus.jackson.map.JsonMappingException: No serializer found for class DataClass and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS)

I found there were two ways to get past that error. The first was to use the Jackson annotations to define properties more directly. The other was to add getters and setters to the class. Here is my DataClass with both configurations.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import java.util.ArrayList;
import java.util.List;
 
import org.codehaus.jackson.annotate.JsonAutoDetect;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;
 
@JsonAutoDetect   // use this annotation if you don't have getters and setters for each JsonProperty
//@JsonIgnoreProperties(ignoreUnknown = true)    // use this if there isn't an exact correlation between JSON and class properties
public class DataClass {
 
  //@JsonProperty("theid") // use this if the property in JSON has a different identifier than your class
  @JsonProperty
  private int id = 1;
 
  @JsonProperty
  private String name = "Test Class";
 
  @JsonProperty
  private List<String> messages = new ArrayList<String>() {
    {
      add("msg 1");
      add("msg 2");
      add("msg 3");
    }
  };
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import java.util.ArrayList;
import java.util.List;
 
public class DataClass {
 
  private int id = 1;
 
  private String name = "Test Class";
 
  private List<String> messages = new ArrayList<String>() {
    {
      add("msg 1");
      add("msg 2");
      add("msg 3");
    }
  };
 
  public String toString() {
    return "User [id=" + id + ", name=" + name + ", " + "messages=" + messages + "]";
  }
  public int getId() {
    return id;
  }
  public void setId(int id) {
    this.id = id;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public List<String> getMessages() {
    return messages;
  }
  public void setMessages(List<String> messages) {
    this.messages = messages;
  }
}

We are now free to modify the doGet and doPost methods in our original servlet to serialize and deserialize the DataClass to and from JSON. Here’s the code for that:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
...
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    PrintWriter out = response.getWriter();
 
    DataClass mydata = new DataClass();
    ObjectMapper mapper = new ObjectMapper();
 
    try {
      // display to console
      out.println(mapper.writeValueAsString(mydata));
    } catch (JsonGenerationException e) {
      e.printStackTrace();
    } catch (JsonMappingException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    out.close();
  }
 
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    PrintWriter out = response.getWriter();
 
    ObjectMapper mapper = new ObjectMapper();
 
    try {
      // read from file, convert it to user class
      DataClass user = mapper.readValue(request.getReader(), DataClass.class);
      // display to console
      out.println(user);
    } catch (JsonGenerationException e) {
      e.printStackTrace();
    } catch (JsonMappingException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    out.close();
  }
...

Now you can easily serialize data to and from JSON using Jackson and POJOs without the need for a mapping file. There are even convenient annotations available that allow you to accommodate differences between the JSON and POJO properties.

Comments

  1. Great tutorial. thanks a lot!
    saved me a lot of time

  2. thank you!!

  3. very helpful ! thank you 🙂

  4. You may want to look at using json-io (https://github.com/jdereg/json-io) or gson (https://code.google.com/p/google-gson/) instead of Jackson for Java JSON serialization. Both handle templates and interfaces better than Jackson. Both libraries perform very fast serialization. Json-io is less than 100K in size and has no dependencies on other libraries besides JDK.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.