gpt4 book ai didi

java/jackson - 链式@JsonValue 注释和反序列化

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:45:37 26 4
gpt4 key购买 nike

我有以下结构。我知道这看起来很奇怪,但我正在用这个例子模拟我们的代码:

public static class StringWrapper {
protected final String s;

@JsonValue
public String getS() {
return s;
}

public StringWrapper(final String s) {
this.s = s;
}
}

public static class StringWrapperOuter {
protected final StringWrapper s;

@JsonValue
public StringWrapper getS() {
return s;
}

public StringWrapperOuter(final StringWrapper s) {
this.s = s;
}
}

public static class POJO {
protected final List<StringWrapperOuter> data;

public List<StringWrapperOuter> getData() {
return data;
}

public POJO(final List<StringWrapperOuter> data) {
this.data = data;
}

public POJO() {
data = Collections.emptyList();
}
}

POJO 的序列化给出了预期的 JSON 字符串数组:

<mapper>.writeValue(System.out, new POJO(Arrays.asList(new StringWrapperOuter(new StringWrapper("a")), new StringWrapperOuter(new StringWrapper("b")), new StringWrapperOuter(new StringWrapper("c")))));

{"data":["a","b","c"]}

如何将此 JSON 字符串反序列化为 POJO 类型的对象?

<mapper>.readValue("{\"data\":[\"a\",\"b\",\"c\"]}", POJO.class);

映射器很难识别输入,因为两个 @JsonValue 注释是链接在一起的。它给出了以下异常:

Caused by: com.fasterxml.jackson.databind.JsonMappingException: Can not instantiate value of type [simple type, class StringWrapperOuter] from String value ('a'); no single-String constructor/factory method
at [Source: {"data":["a","b","c"]}; line: 1, column: 10] (through reference chain: POJO["data"]->java.util.ArrayList[0])

最佳答案

@JsonValue 用于序列化。反序列化的类似注释是 @JsonCreator

注释你的构造函数

@JsonCreator
public StringWrapper(final String s) {
this.s = s;
}

@JsonCreator
public StringWrapperOuter(final StringWrapper s) {
this.s = s;
}

关于java/jackson - 链式@JsonValue 注释和反序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27696720/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com