您的位置:首页 > 其它

jaxb工具类

2016-02-24 13:58 225 查看
 
import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

@SuppressWarnings({ "unchecked" })
public class XmlUtil<T> {

public static String toXml(Object req, Class<?> c) {
try {
StringWriter writer = new StringWriter();
JAXBContext context = JAXBContext.newInstance(c);
javax.xml.bind.Marshaller marshaller = context.createMarshaller();
marshaller.marshal(req, new StreamResult(writer));
String result = writer.toString();
writer.close();
return result;
} catch (Exception e) {

throw new RuntimeException(e.getMessage(), e);
}
}

public static <T> T toObj(String respXml, Class<T> c) {
try {
JAXBContext context = JAXBContext.newInstance(c);
javax.xml.bind.Unmarshaller unmarshaller = context.createUnmarshaller();
StringReader reader = new StringReader(respXml);
T result = (T) unmarshaller.unmarshal(new StreamSource(reader));
reader.close();
return result;
} catch (Exception e) {

throw new RuntimeException(e.getMessage(), e);
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  jaxb