简体   繁体   English

如何让Jackson使用一种方法将类序列化为JSON?

[英]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: 当Jackson序列化MyClass一个实例时,它将如下所示:

{"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? 我是否可以在Test类中添加任何注释, toCustomString()在序列化Test对象时强制Jackson调用toCustomString()方法?

I'd like to see one of the following outputs when Jackson serializes an instance of MyClass : 当Jackson序列化MyClass一个实例时,我想看到以下输出之一:

{"t":"50.50"}

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

You are looking for @JsonProperty annotation. 您正在寻找@JsonProperty注释。 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. 此外,杰克逊一直否认要序列化MyClass ,所以为了避免问题,你可以添加一个简单的getter到t属性。

If you want to produce 如果你想生产

{"t":"50.50"}

you can use @JsonValue which indicates 你可以用@JsonValue来表示

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. 注释“getter”方法的结果(这意味着签名必须是getter;非void返回类型,没有args)将被用作实例序列化的单个值。

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

If you want to produce 如果你想生产

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

you can use a custom JsonSerializer . 您可以使用自定义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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM