南瓜先生~xml字串和javaBean互轉
阿新 • • 發佈:2018-12-31
1.寫一個工具類:
public static String convertToXml(Object obj, String encoding) { String result = null; try { JAXBContext context = JAXBContext.newInstance(obj.getClass()); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding); StringWriter writer = new StringWriter(); marshaller.marshal(obj, writer); result=writer.toString(); } catch (Exception e) { e.printStackTrace(); } return result; }
2.建立三個bean
2.1.Student作為根節點,用到的註解如下:
@XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name = "root") @XmlType(propOrder = {}) public class Student { @XmlElement(name="head") private Head head; @XmlElement(name = "body") private Body body;
2.2Head、Body作為根節點的子節點
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(propOrder = { "name", "desc" })
public class Body {
@XmlElement
private String name;
@XmlElement
private String desc;
3.測試一下:
Student student = new Student(); Body body = new Body(); Head head=new Head(); head.setDesc("1"); head.setName("111"); body.setDesc("2"); body.setName("222"); student.setBody(body); student.setHead(head); String str = JaxbUtil.convertToXml(student,"GBK"); System.out.println(str);
這樣基本實現javaBean轉成xml。
4.xml字串轉成javaBean,一個方法足以。
public static T converyToJavaBean(String xml, Class c) {
T t = null;
try {
JAXBContext context = JAXBContext.newInstance(c);
Unmarshaller unmarshaller = context.createUnmarshaller();
t = (T) unmarshaller.unmarshal(new StringReader(xml));
} catch (Exception e) {
e.printStackTrace();
}
return t;
}