mtyurt
mtyurt

Reputation: 3449

Serializing an empty class (with no field)

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.

Upvotes: 2

Views: 5298

Answers (2)

Alan Teals
Alan Teals

Reputation: 471

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>   

Upvotes: 1

Michał Ziober
Michał Ziober

Reputation: 38665

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.

Upvotes: 3

Related Questions