Convert java object with org.w3c.dom.Element to string and get error when convert back

前端 未结 1 1986
慢半拍i
慢半拍i 2021-01-27 04:33

I have wrapper class:

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Wrapper {
    private String id;
    private int number;
    private Element inte         


        
相关标签:
1条回答
  • 2021-01-27 04:43

    You have two options:

    1. Change internal type to Document or Node.
    2. Write custom deserialiser which will do the same as you in line: Element element = document.getDocumentElement();

    Custom deserialiser:

    class ElementDeserializer extends DOMDeserializer<Element> {
    
        private static final long serialVersionUID = 1L;
    
        public ElementDeserializer() {
            super(Element.class);
        }
    
        @Override
        public Element _deserialize(String value, DeserializationContext ctxt)
            throws IllegalArgumentException {
            return parse(value).getDocumentElement();
        }
    }
    

    You can register it as below:

    SimpleModule elementModule = new SimpleModule();
    elementModule.addDeserializer(Element.class, new ElementDeserializer());
    
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(elementModule);
    

    But I suggest to stay with custom deserialisers for Documen - com.fasterxml.jackson.databind.ext.DOMDeserializer.DocumentDeserializer and Node - com.fasterxml.jackson.databind.ext.DOMDeserializer.NodeDeserializer.

    0 讨论(0)
提交回复
热议问题