Skip to content

Instantly share code, notes, and snippets.

@yanhua365
Last active December 30, 2015 07:59
Show Gist options
  • Select an option

  • Save yanhua365/7799979 to your computer and use it in GitHub Desktop.

Select an option

Save yanhua365/7799979 to your computer and use it in GitHub Desktop.
JAXB2反序列化XML到JavaBean,以及序列化到字符串的功能。
private String coverToXml(FilesInfoBean info) {
StringWriter writer = new StringWriter();
try {
JAXBContext context = JAXBContext.newInstance(info.getClass());
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); //格式化
marshaller.marshal(info, writer);
} catch (JAXBException e) {
e.printStackTrace();
}
return writer.toString();
}
protected UpdateRequestBody parseBody(String body, Class<? extends UpdateRequestBody> requestType) throws BadUpdateRequestException{
try {
JAXBContext context = JAXBContext.newInstance(requestType);
Unmarshaller unmarshaller = context.createUnmarshaller();
return (UpdateRequestBody)unmarshaller.unmarshal(new StringReader(body));
} catch (JAXBException e) {
logger.error("It occurs error when parsing update request body.Body is:\n\n{}", e, body);
throw new BadUpdateRequestException.BodyError("It occurs error when parsing update request body.", e);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment