Is it possible to serialize object to JSON using toString method without custom serializer?

Viewed 1875

I have this class:

public class JsonUser {

    private final String id;
    private final String email;

    public JsonUser(String id, String email) {
        this.id = id;
        this.email = email;
    }

    @Override
    public String toString() {
        JsonObject json = new JsonObject();
        json.addProperty("id", user.id());
        json.addProperty("email", user.email());
        return json.toString();
    }

}

As you see, JsonUser::toString returns a JSON string. I'm wondering if there is any way to tell Jackson to serialize JsonUser by calling toString method, instead of by fields/properties.

Is it possible to achieve that without using @JsonSerialize with a custom serializer?

1 Answers

If you annotate the toString() method with @JsonValue Jackson will use that for serialization. You can also annotate a String constructor with @JsonCreator for deserialization.

Related