[java] Serializing with Jackson (JSON) - getting "No serializer found"?

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();
}

This question is related to java json jackson

The answer is


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


The problem may be because you have declared variable as private. If you change it to public, it works.

Better option is to use getter and setter methods for it.

This will solve the issue!


I had a similar problem with lazy loading via the hibernate proxy object. Got around it by annotating the class having lazy loaded private properties with:

@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})

If you can edit the class containing that object, I usually just add the annotation

import com.fasterxml.jackson.annotation.JsonIgnore;

@JsonIgnore 
NonSerializeableClass obj;

This error is also thrown if you forget to add the .build() method onto your return status.

return Response.status(Status.OK);         // fails
return Response.status(Status.OK).build(); // works

I got the following error without build() method:

org.codehaus.jackson.map.JsonMappingException: No serializer found for class com.sun.jersey.core.spi.factory.ResponseBuilderImpl

SpringBoot2.0 ,I resolve it by follow code:

@Bean public ObjectMapper objectMapper() {
 return new ObjectMapper().disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);}

For Oracle Java applications, add this after the ObjectMapper instantiation:

mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);

Please use this at class level for the bean:

@JsonIgnoreProperties(value={"hibernateLazyInitializer","handler","fieldHandler"})

Here are the three options:

  1. Data/class that's been accessed needs to be public
  2. If not public, add getters & setters
  3. Or add @JsonIgnore("context")

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.


I just had only getters , after adding setters too , problems resolved.


If you use Lomdok libraray (https://projectlombok.org/) then add @Data (https://projectlombok.org/features/Data) annotation to your data object class.


I found at least three ways of doing this:

  1. Add public getters on your entity that you try to serialize;
  2. Add an annotation at the top of the entity, if you don't want public getters. This will change the default for Jackson from Visbility=DEFAULT to @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY) where any access modifiers are accepted;
  3. Change your ObjectMapper globally by setting objectMapperInstance.setVisibility(JsonMethod.FIELD, Visibility.ANY);. This should be avoided if you don't need this functionality globally.

Choose based on your needs.


Add a

getter

and a

setter

and the problem is solved.


in spring boot 2.2.5

after adding getter and setter

i added @JsonIgnore on top of the field.


adding setter and getter will also solve the issue as it fixed for me. For Ex:

public class TestA {
    String SomeString = "asd";

    public String getSomeString () {        return SomeString ;     }

    public void setSomeString (String SS ) {        SomeString = SS ;   } 
}

Though I added getters and setters I was getting the same error. Later I found a bug, that is by Sonar's advice I cgahnged the getters and setters as protected which was causing the issue. Once I fixed that it worked as exppected.


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)

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to jackson

No Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value How to convert JSON string into List of Java object? Deserialize Java 8 LocalDateTime with JacksonMapper java.lang.IllegalArgumentException: No converter found for return value of type java.lang.ClassNotFoundException: com.fasterxml.jackson.annotation.JsonInclude$Value How to modify JsonNode in Java? Deserialize JSON with Jackson into Polymorphic Types - A Complete Example is giving me a compile error Convert Map to JSON using Jackson Required request body content is missing: org.springframework.web.method.HandlerMethod$HandlerMethodParameter