为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

尚方宝剑之说 2022-08-17 15:20:39
我有包装类:@Data@NoArgsConstructor@AllArgsConstructorpublic class Wrapper {    private String id;    private int number;    private Element internal;}我有内部类:@XmlRootElement@Data@AllArgsConstructor@NoArgsConstructorpublic 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>"}
查看完整描述

1 回答

?
收到一只叮咚

TA贡献1821条经验 获得超4个赞

您有两种选择:

  1. 将类型更改为 或 。internalDocumentNode

  2. 编写自定义 deserialiser,它将在行中执行与您相同的操作: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();

    }

}

您可以按如下方式注册:


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


查看完整回答
反对 回复 2022-08-17
  • 1 回答
  • 0 关注
  • 216 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信