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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29550006/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 15:29:12  来源:igfitidea点击:

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

javajsonserializationHymansoncustomization

提问by pacoverflow

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 Hymanson serializes an instance of MyClass, it will look like the following:

当 Hymanson 序列化 的实例时MyClass,它将如下所示:

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

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

Is there any annotation I can put in the Testclass to force Hymanson to invoke the toCustomString()method whenever serializing a Testobject?

我可以在Test类中添加任何注释以强制 HymansontoCustomString()在序列化Test对象时调用该方法吗?

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

当 Hymanson 序列化 的实例时,我希望看到以下输出之一MyClass

{"t":"50.50"}

{"t":"50.50"}

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

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

采纳答案by Sotirios Delimanolis

If you want to produce

如果你想生产

{"t":"50.50"}

you can use @JsonValuewhich indicates

您可以使用@JsonValuewhich 表示

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 的签名;非空返回类型,没有参数)的结果将用作实例序列化的单个值。

@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;

回答by mtyurt

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

您正在寻找@JsonProperty注释。只需将其放入您的方法中:

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

Also, Hymanson consistently denied to serialize MyClass, so to avoid problems you can add a simple getter to tproperty.

此外,Hymanson 一直拒绝序列化MyClass,因此为了避免出现问题,您可以向t属性添加一个简单的 getter 。