No serializer found for class & no props to create BeanSerializer" - Jackson

I am trying to serialize an ArrayList of objects of the Person class, defined as follows:

public class Person {
    String name;
    String age 
    List<String> education = new ArrayList<String> ();
    List<String> family = new ArrayList<String> (); 
    List<String> previousjobs = new ArrayList<String>(); 
}

I’m using the following code to serialize the ArrayList and write it as a Json file:

Writer out = new PrintWriter("./test.json");
mapper.writerWithDefaultPrettyPrinter().writeValueas(out, persons);

However, I’m receiving the following error message:

No serializer found for class ~~~~~~ and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: java.util.ArrayList[0])`

I tried adding mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS) but it made all the Person objects empty. What am I doing wrong?

The error message suggests that there is no serializer found for the Person class. To fix this issue, you need to add annotations to the Person class to help the ObjectMapper correctly serialize the Person objects to JSON.

Here’s an example of how you can annotate the Person class:

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonInclude;

@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Person {
    @JsonProperty("name")
    private String name;
    @JsonProperty("age")
    private String age;
    @JsonProperty("education")
    private List<String> education = new ArrayList<>();
    @JsonProperty("family")
    private List<String> family = new ArrayList<>(); 
    @JsonProperty("previous_jobs")
    private List<String> previousJobs = new ArrayList<>();

    // getters and setters
}

Explanation:

  • @JsonProperty is used to specify the JSON property name for each field. This is important because the default property names are based on the Java field names, which may not match the desired JSON property names.
  • @JsonInclude is used to exclude empty lists from the output. This is important because the default behavior of the ObjectMapper is to include all fields, even if they are empty, which can result in a large and cluttered JSON output.

Once you have added these annotations, you can try serializing the ArrayList again and writing it to a JSON file:

ObjectMapper mapper = new ObjectMapper();
Writer out = new PrintWriter("./test.json");
mapper.writerWithDefaultPrettyPrinter().writeValue(out, persons);

This should serialize the ArrayList of Person objects to JSON without any errors.