我有包装类:
@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>"
}
收到一只叮咚
相关分类