Serializing with Jackson (JSON) - getting "No serializer found"?
Question
I get the an exception when trying to serialize a very simple object using Jackson. The error:
org.codehaus.jackson.map.JsonMappingException: No serializer found for class MyPackage.TestA and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS) )
Below is the simple class and code to serialize.
Can anyone tell my why I get this error?
public class TestA {
String SomeString = "asd";
}
TestA testA = new TestA();
ObjectMapper om = new ObjectMapper();
try {
String testAString = om.writeValueAsString(testA); // error here!
TestA newTestA = om.readValue(testAString, TestA.class);
} catch (JsonGenerationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Accepted Answer
As already described, the default configuration of an ObjectMapper
instance is to only access properties that are public fields or have public getters/setters. An alternative to changing the class definition to make a field public or to provide a public getter/setter is to specify (to the underlying VisibilityChecker
) a different property visibility rule. Jackson 1.9 provides the ObjectMapper.setVisibility()
convenience method for doing so. For the example in the original question, I'd likely configure this as
myObjectMapper.setVisibility(JsonMethod.FIELD, Visibility.ANY);
For Jackson >2.0:
myObjectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
For more information and details on related configuration options, I recommend reviewing the JavaDocs on ObjectMapper.setVisibility()
.
Read more... Read less...
For Jackson to serialize that class, the SomeString
field needs to either be public
(right now it's package level isolation) or you need to define getter and setter methods for it.
The problem in my case was Jackson was trying to serialize an empty object with no attributes nor methods.
As suggested in the exception I added the following line to avoid failure on empty beans:
For Jackson 1.9
myObjectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
For Jackson 2.X
myObjectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
You can find a simple example on jackson disable fail_on_empty_beans
I had the same problem for a child class where I had control, object mapper was in a common module and was inaccessible. I solved it by adding this annotation for my child class whose object was to be serialized.
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
If you can edit the class containing that object, I usually just add the annotation
import com.fasterxml.jackson.annotation.JsonIgnore;
@JsonIgnore
NonSerializeableClass obj;