如何将json反序列化为政治类?

我需要反序列化JSON才能根据属性之一的类型进行分类。 我有以下JSON:

{
   "type":"text","message": "Hello"
}

我有以下Enum

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属性,如果typeTEXT则要反序列化为TextMessage类,否则为DateMessage类。

我该怎么做?你能给我一些想法或例子吗?

wxj343302733 回答:如何将json反序列化为政治类?

您的方法有点混乱,但是也许您可以做类似的事情:

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() {
    }
}
本文链接:https://www.f2er.com/3123831.html

大家都在问