@SneakyThrows
    public static <T> String convertToXml(T obj) {
        require(obj);

        JAXBContext jaxbContext = JAXBContext.newInstance(obj.getClass());
        Marshaller marshaller = jaxbContext.createMarshaller();
        //marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // pretty
        //marshaller.setProperty(Marshaller.JAXB_ENCODING, "ISO-8859-1"); // specify encoding
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        marshaller.marshal(obj, stream);
        return stream.toString(Contract.Utf8);
    }

    @SneakyThrows
    public static <T> T convertFromXml(String xml, Class<T> type) {
        require(xml, type);

        JAXBContext jaxbContext = JAXBContext.newInstance(type);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        byte[] data = xml.getBytes(Contract.Utf8);
        ByteArrayInputStream stream = new ByteArrayInputStream(data);
        return (T) unmarshaller.unmarshal(stream);
    }

 

相关文章:

  • 2021-07-26
  • 2022-12-23
  • 2021-09-06
  • 2021-12-26
  • 2021-10-27
  • 2022-12-23
  • 2022-12-23
  • 2021-06-28
猜你喜欢
  • 2022-03-02
  • 2021-11-14
  • 2021-10-25
  • 2021-07-14
  • 2022-12-23
  • 2021-08-11
  • 2021-10-04
相关资源
相似解决方案