Serializing an empty class (with no field)

我怕爱的太早我们不能终老 提交于 2021-02-10 07:18:16

问题


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:

  1. Serialization features.
  2. Deserialization Features.
  3. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!