gpt4 book ai didi

java - Jackson:根据字段存在选择子类进行反序列化

转载 作者:行者123 更新时间:2023-12-02 03:01:01 25 4
gpt4 key购买 nike

我有以下模型:

public abstract class A {
String commonField;
}

public class B extends A {
}

public class C extends A {
String customField;
}

如何根据存在的“customField”字段判断选择类(B 或 C)?

{ "commonField" : "..."} --> B instance

{ "commonField" : "...", "customField" : null} --> B instance

{ "commonField" : "...", "customField" : "..."} --> C instance

最佳答案

试试这个会有什么帮助

ObjectMapper mapper = new ObjectMapper();

String json = "{ \"commonField\" : \"...\", \"customField\"}";

JsonNode jsonNode = mapper.readTree( json );

A a; // class a

if(jsonNode.has( "customField" )) {

a = mapper.convertValue( jsonNode, C.class );
} else {

a = mapper.convertValue( jsonNode, B.class );
}

关于java - Jackson:根据字段存在选择子类进行反序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42348140/

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