对象和xml之间的转换

1.将entity转换成byte[]

public static byte[] jaxbToByte(JAXBElement<UserRequest> request) {
        ByteArrayOutputStream baos = null;
        try {
            baos = new ByteArrayOutputStream();
            JAXBContext jc = JAXBContext.newInstance(UserRequest.class);
            Marshaller marshaller = jc.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.marshal(request, baos);

            return baos.toByteArray();
        }
        catch (JAXBException e) {
            LOG.info("JAXBException captured during Marshalling UserRequest " + e);
            throw new IllegalArgumentException("JAXBException captured during Marshalling UserRequest " + e);
        }
    }

 2.byte[]转换成Entity

 

public UserRequest getUserRequest(byte[] bs) {
        ByteArrayInputStream bais = new ByteArrayInputStream(bs);

        try {
            JAXBContext jc = JAXBContext.newInstance(UserRequest.class);
            Unmarshaller unMarshaller = jc.createUnmarshaller();
            JAXBElement<UserRequest> dataset = (JAXBElement<UserRequest>) unMarshaller.unmarshal(new StreamSource(bais), UserRequest.class);
            return dataset.getValue();
        }
        catch (JAXBException e) {
            LOG.log(Level.INFO, "error in unmarshall user soap body", e);
            return null;
        }
    }

 

你可能感兴趣的:(xml)