8

Let's say I have the following classes:

public class MyClass {
    private Test t;

    public MyClass() {
        t = new Test(50);
    }
}

public class Test {
    private int test;

    public Test(int test) {
        this.test = test;
    }

    public String toCustomString() {
        return test + "." + test;
    }
}

When Jackson serializes an instance of MyClass, it will look like the following:

{"t":{"test":50}}

Is there any annotation I can put in the Test class to force Jackson to invoke the toCustomString() method whenever serializing a Test object?

I'd like to see one of the following outputs when Jackson serializes an instance of MyClass:

{"t":"50.50"}

{"t":{"test":"50.50"}}

pacoverflow
  • 3,726
  • 11
  • 41
  • 71

2 Answers2

7

If you want to produce

{"t":"50.50"}

you can use @JsonValue which indicates

that results of the annotated "getter" method (which means signature must be that of getters; non-void return type, no args) is to be used as the single value to serialize for the instance.

@JsonValue
public String toCustomString() {
    return test + "." + test;
}

If you want to produce

{"t":{"test":"50.50"}}

you can use a custom JsonSerializer.

class TestSerializer extends JsonSerializer<Integer> {
    @Override
    public void serialize(Integer value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
        jgen.writeString(value + "." + value);
    }
}
...
@JsonSerialize(using = TestSerializer.class)
private int test;
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
6

You are looking for @JsonProperty annotation. Just put it to your method:

@JsonProperty("test")
public String toCustomString() {
    return test + "." + test;
}

Also, Jackson consistently denied to serialize MyClass, so to avoid problems you can add a simple getter to t property.

mtyurt
  • 3,369
  • 6
  • 38
  • 57
  • Jackson looks for getters and @JsonProperty annotated methods while serializing. The output would be `{"t":"50.50"}` in your case. – mtyurt Apr 09 '15 at 22:25
  • Oh sorry, I missed the point. To produce your output, property value should be `test`, I'm editing now. – mtyurt Apr 09 '15 at 22:28
  • 1
    I like your answer as an easier alternative to producing `{"t":{"test":"50.50"}}` instead of using a custom serializer. Thanks. – pacoverflow Apr 09 '15 at 22:51