javajsonserializationjackson

Jackson: No serializer found for class ~~~~~ and no properties discovered to create BeanSerializer


I have an ArrayList of a class that looks like this:

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 want to write this list as Json and tried this code:

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

and got this 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 for some unknown reasons.

What am I getting wrong?


Solution

  • Excerpt from here:

    By default, Jackson 2 will only work with with fields that are either public, or have a public getter methods – serializing an entity that has all fields private or package private will fail:

    Your Person has all fields package protected and without getters thus the error message. Disabling the message naturally does not fix the problem since the class is still empty from Jackson's point of view. That is why you see empty objects and it is better to leave the error on.

    You need to either make all fields public, like:

    public class Person {
        public String name;
        // rest of the stuff...
    }
    

    or create a public getter for each field (and preferably also set fields private), like:

    public class Person {
        private String name;
    
        public String getName() {
            return this.name;
        }
        // rest of the stuff...
    }