Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 542
7029279 Avatar asked Jan 03 '20 12:01

7029279


People also ask

What is Jackson object serialization?

Jackson is a solid and mature JSON serialization/deserialization library for Java. The ObjectMapper API provides a straightforward way to parse and generate JSON response objects with a lot of flexibility.

What is Fail_on_empty_beans?

FAIL_ON_EMPTY_BEANS. Feature that determines what happens when no accessors are found for a type (and there are no annotations to indicate it is meant to be serialized).

Does Jackson use getters and setters?

Let's start with Jackson's default behavior during deserialization. Jackson can't deserialize into private fields with its default settings. Because it needs getter or setter methods.

What is the use of @JsonSerialize?

@JsonSerialize is used to specify custom serializer to marshall the json object.


1 Answers

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...
}
like image 200
pirho Avatar answered Dec 09 '22 22:12

pirho