Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have Jackson use a method to serialize a class to JSON?

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"}}

like image 344
pacoverflow Avatar asked Apr 09 '15 22:04

pacoverflow


2 Answers

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;
like image 114
Sotirios Delimanolis Avatar answered Nov 15 '22 16:11

Sotirios Delimanolis


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.

like image 33
mtyurt Avatar answered Nov 15 '22 17:11

mtyurt