问题
I have the following class:
class Foo {
@JsonCreator
public Foo()
{
}
}
And I get the following exception:
com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class Foo and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) )
It cannot be serialized in this way. And I don't want to ignore the value, I just want to see {}
output as JSON.
Any help will be appreciated.
回答1:
You have to disable SerializationFeature.FAIL_ON_EMPTY_BEANS
option. See below example:
ObjectMapper mapper = new ObjectMapper();
mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
System.out.println(mapper.writeValueAsString(new Foo()));
Above program prints:
{}
See also:
- Serialization features.
- Deserialization Features.
- Mapper Features.
回答2:
in this case I would use the @JsonSerialize annotation:
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@JsonSerialize
public class Foo {
public Foo() {}
}
Note you will need add this dependency, for maven:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
来源:https://stackoverflow.com/questions/25720509/serializing-an-empty-class-with-no-field