使用 org.w3c.dom.Element 将 java 对象转换为字符串,并在转换回来时出错

我有包装类:


@Data

@NoArgsConstructor

@AllArgsConstructor

public class Wrapper {

    private String id;

    private int number;

    private Element internal;

}

我有内部类:


@XmlRootElement

@Data

@AllArgsConstructor

@NoArgsConstructor

public class Payment {

    private BigDecimal amount;

    private String account;

}

我创建 ,将其转换为 并设置为 .之后,我将包装器转换为字符串,使用Json JacksonPaymentorg.w3c.dom.ElementWrapper


之后,我尝试以另一种方式转换 - 字符串到对象并得到错误。


public class Main {

    public static void main(String[] args) throws JAXBException, ParserConfigurationException, IOException {


        ObjectMapper mapper = new ObjectMapper();


        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();

        JAXBContext context = JAXBContext.newInstance(Payment.class);

        Marshaller marshaller = context.createMarshaller();


        //create paymant

        Payment payment = new Payment(BigDecimal.valueOf(100), "666");


        //convert to Element

        marshaller.marshal(payment, document);

        Element element = document.getDocumentElement();


        //set Paymant as Element to Wrapper

        Wrapper wrapper = new Wrapper("123321", 987, element);


        //convert Wrapper to string

        String wrapperAsString = mapper.writeValueAsString(wrapper);


        System.out.println(wrapperAsString);


        //convert the other way

        Wrapper restoreWrapper = mapper.readValue(wrapperAsString, Wrapper.class);


    }

}

当我将包装器转换为字符串时,我得到这个结果:


{

    "id": "123321",

    "number": 987,

    "internal": "<?xml version=\"1.0\" encoding=\"UTF-16\"?>\n<payment><account>666</account><amount>100</amount></payment>"

}


尚方宝剑之说
浏览 217回答 1
1回答

收到一只叮咚

您有两种选择:将类型更改为 或 。internalDocumentNode编写自定义 deserialiser,它将在行中执行与您相同的操作:Element element = document.getDocumentElement();Custom deserialiser:class ElementDeserializer extends DOMDeserializer<Element> {&nbsp; &nbsp; private static final long serialVersionUID = 1L;&nbsp; &nbsp; public ElementDeserializer() {&nbsp; &nbsp; &nbsp; &nbsp; super(Element.class);&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; public Element _deserialize(String value, DeserializationContext ctxt)&nbsp; &nbsp; &nbsp; &nbsp; throws IllegalArgumentException {&nbsp; &nbsp; &nbsp; &nbsp; return parse(value).getDocumentElement();&nbsp; &nbsp; }}您可以按如下方式注册:SimpleModule elementModule = new SimpleModule();elementModule.addDeserializer(Element.class, new ElementDeserializer());ObjectMapper mapper = new ObjectMapper();mapper.registerModule(elementModule);但我建议留在定制的除甲醚 - 和 - .Documencom.fasterxml.jackson.databind.ext.DOMDeserializer.DocumentDeserializerNodecom.fasterxml.jackson.databind.ext.DOMDeserializer.NodeDeserializer
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java