gpt4 book ai didi

java - 按属性反序列化 JSON

转载 作者:行者123 更新时间:2023-11-30 08:00:01 25 4
gpt4 key购买 nike

我有一个简单的包装类。

class Wrapper {
int id;
Object command;
}

command 可能是我从外部获取的对象,并且我无法创建一个接口(interface)来将可能的类型保存在一起。我想简单地序列化它:

String json = objectMapper.writeValueAsString(wrapper);

这样我就得到:

{"id":"1","command":{"type" : "objectType", "key0": "val0", ... other properties...}}

理想情况下,我会构建一个注册表,其中包含 type 的可能值和相应的类名作为值,这样我就可以像这样反序列化它:

Wrapper wrapper = objectMapper.readValue(bytes, Wrapper.class);

(objectMappercom.fasterxml.jackson.databind.ObjectMapper)

有没有办法通过 Jackson 实现这一目标?

最佳答案

您可以使用the Jackson polymorphic type handling 。您可以使用 @JsonTypeXXX 注释来声明命令属性的类型。

这是一个完整的示例:

public class JacksonTypeInfoOnObject {

public static class Bean {
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(Command1.class),
@JsonSubTypes.Type(Command2.class)
})
public final Object command;

@JsonCreator
public Bean(@JsonProperty("command") final Object command) {this.command = command;}

@Override
public String toString() {
return "Bean{" +
"command=" + command +
'}';
}
}

@JsonTypeName("cmd1")
public static class Command1 {
@Override
public String toString() {
return "Command1{}";
}
}

@JsonTypeName("cmd2")
public static class Command2 {
@Override
public String toString() {
return "Command2{}";
}
}


public static void main(String[] args) throws IOException {
final ObjectMapper mapper = new ObjectMapper();
mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
final List<Bean> list = Arrays.asList(
new Bean(new Command1()),
new Bean(new Command2()));
final String json = mapper.writeValueAsString(list);
System.out.println(json);
final List<Bean> values = mapper.readValue(json, new TypeReference<List<Bean>>() {});
System.out.println(values);
}
}

输出:

[{"command":{"type":"cmd1"}},{"command":{"type":"cmd2"}}]
[Bean{command=Command1{}}, Bean{command=Command2{}}]

关于java - 按属性反序列化 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32097038/

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