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?
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.
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).
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.
@JsonSerialize is used to specify custom serializer to marshall the json object.
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...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With