Jackson deserialize based on type

后端 未结 4 1618
夕颜
夕颜 2020-12-15 22:09

Lets say I have JSON of the following format:

{
    \"type\" : \"Foo\"
    \"data\" : {
        \"object\" : {
            \"id\" : \"1\"
            \"fizz\         


        
4条回答
  •  执笔经年
    2020-12-15 22:45

    I think it is rather straight-forward. You probably have a super class that has properties for metadata and owner, so rather than making it truly generic, you could substitute T for your super class. But basically, you will have to parse the name of the class from the actual JSON string, which in your example would look something like this:

    int start = jsonString.indexOf("type");
    int end = jsonString.indexOf("data");
    Class actualClass = Class.forName(jsonString.substring(start + 4, end - 2)); // that of course, is approximate - based on how you format JSON
    

    and overall code could be something like this:

    public static  T deserialize(String xml, Object obj)
            throws JAXBException {
    
        T result = null;
    
        try {
    
            int start = jsonString.indexOf("type");
            int end = jsonString.indexOf("data");
            Class actualClass = Class.forName(jsonString.substring(start + 4, end - 2)); 
    
            JAXBContextFactory factory = JAXBContextFactory.getInstance();
            JAXBContext jaxbContext = factory.getJaxBContext(actualClass);
    
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    
            // this will create Java object
            try (StringReader reader = new StringReader(xml)) {
                result = (T) jaxbUnmarshaller.unmarshal(reader);
            }
    
        } catch (JAXBException e) {
            log.error(String
                    .format("Exception while deserialising the object[JAXBException] %s\n\r%s",
                            e.getMessage()));
        }
    
        return result;
    }
    

提交回复
热议问题