我需要将 JSON 反序列化为类,具体取决于其中一个属性的类型。 我有以下 JSON:
{
"type":"text",
"message": "Hello"
}
我有以下枚举
:
public enum MyEnumType {
TEXT("text"),
DATE("date")
private final String type;
MyEnumType(String type) {
this.type = type;
}
}
我的 Abstract
类如下所示:
public abstract class MyClass {
public MyEnumType type;
}
我有一些扩展MyClass
的类
public class TextMessage extends MyClass {
public String message;
}
public class DateMessage extends MyClass {
...
}
我需要编写一些如下所示的代码:
ObjectMapper mapper = new ObjectMapper();
MyClass instance = mapper.readValue(json, MyClass.class);
并且必须获取依赖于 type
属性的实例,如果 type
是 TEXT
才能反序列化为 TextMessage
类否则到 DateMessage
类。
我该怎么做?你能给我一些想法或例子吗?
最佳答案
你的方法有点困惑,但也许你可以做类似的事情:
public class Test {
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
String json = "{\"type\":\"text\", \"message\": \"Hello\"}";
// create ObjectMapper instance
ObjectMapper objectMapper = new ObjectMapper();
MainObj mo = objectMapper.readValue(json, MainObj.class);
System.out.println("type: " + mo.getType());
MyClass instance = null;
if (mo.getType().equalsIgnoreCase("text")) {
// Do it for the 'text'
} else {
// Do it for the 'date'
}
}
}
class MainObj {
private String type = "";
private Object message = null;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Object getMessage() {
return message;
}
public void setMessage(Object message) {
this.message = message;
}
}
class MyClass {
public MyClass() {
}
}
关于java - 如何将json反序列化为多态类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58802466/