缓存与数据库一致性如何解决,JavaBean与xml互转的方法详解

public class JaxbUtil {

/**

 * JavaBean装换成xml 默认编码UTF-8

 *

 * @param obj

 * @return

 */

public static String converTomXml(Object obj) {

    return converToXml(obj, "UTF-8");

}



/**

 * JavaBean装换成xml

 *

 * @param obj

 * @param encoding

 * @return

 */

private static String converToXml(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;

}



/**

 * xml装换成JavaBean

 *

 * @param xml

 * @param c

 * @return

 */

@SuppressWarnings("unchecked")

public static <T> T converyToJavaBean(String xml, Class<T> 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;

}

}




### 2、简单类型 



(1)单实体类转换



package com.guor.demo.beanToXml;

import java.util.Date;

import javax.xml.bind.annotation.XmlAccessType;

import javax.xml.bind.annotation.XmlAccessorType;

import javax.xml.bind.annotation.XmlAttribute;

import javax.xml.bind.annotation.XmlElement;

import javax.xml.bind.annotation.XmlRootElement;

import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)

@XmlRootElement

@XmlType(name = “book”, propOrder = { “author”, “calendar”, “price”, “id” })

public class Book {

@XmlElement(required = true)

private String author;

@XmlElement(name = "price_1", required = true)

private float price;

@XmlElement

private Date calendar;

@XmlAttribute

private Integer id;



/**

 *

 * @return

 */

public String getAuthor() {

    return author;

}



public void setAuthor(String author) {

    this.author = author;

}



public float getPrice() {

    return price;

}



public void setPrice(float price) {

    this.price = price;

}



public Date getCalendar() {

    return calendar;

}



public void setCalendar(Date calendar) {

    this.calendar = calendar;

}



public Integer getId() {

    return id;

}



public void setId(Integer id) {

    this.id = id;

}



@Override

public String toString() {

    return "Book [author=" + author + ", price=" + price + ", calendar=" + calendar + ", id=" + id + "]";

}

}




(2)test 



package com.guor.demo.beanToXml;

import java.util.Date;

import org.junit.Test;

import javax.xml.bind.JAXBException;

@SuppressWarnings(“unused”)

public class JaxbTest1 {

/**

 * @throws JAXBException

 */

@Test

public void showMarshaller() {

    Book book = new Book();

    book.setId(100);

    book.setAuthor("lin");

    book.setCalendar(new Date());

    book.setPrice(23.56f);

    String str = JaxbUtil.converTomXml(book);

    System.out.println(str);



}



/**

 * @throws JAXBException

 */

@Test

public void showUnMarshaller() {

    String str = "<?xml version =\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" + "<book id =\"100\">"

            + "<author>lin</author>" + "<calendar>2018-9-3T11:58.006</calendar>" + "<price_1>23.56</price_1>"

            + "</book>";

    Book book = JaxbUtil.converyToJavaBean(str, Book.class);

    System.out.println(book);

}

}




 (3)控制台输出



![](https://www.icode9.com/i/ll/?i=20210130084212537.png?,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2d1b3J1aV9qYXZh,size_16,color_FFFFFF,t_70)



### 3、类中包含复杂对象的转换



(1)实体类1



package com.guor.demo.beanToXml;

import javax.xml.bind.annotation.XmlAccessType;

import javax.xml.bind.annotation.XmlAccessorType;

import javax.xml.bind.annotation.XmlAttribute;

import javax.xml.bind.annotation.XmlElement;

import javax.xml.bind.annotation.XmlRootElement;

import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)

@XmlRootElement(name = “student”)

@XmlType(propOrder = {})

public class Student {

@XmlAttribute

private Integer id;

@XmlElement

private String name;

@XmlElement(name = "role")

private Role role;



public Integer getId() {

    return id;

}



public void setId(Integer id) {

    this.id = id;

}



public String getName() {

    return name;

}



public void setName(String name) {

    this.name = name;

}



public Role getRole() {

    return role;

}



public void setRole(Role role) {

    this.role = role;

}



@Override

public String toString() {

    return "Student [id=" + id + ", name=" + name + ", role=" + role + "]";

}

}




(2)实体类2 



package com.guor.demo.beanToXml;

import javax.xml.bind.annotation.XmlAccessType;

import javax.xml.bind.annotation.XmlAccessorType;

import javax.xml.bind.annotation.XmlElement;

import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)

@XmlType(propOrder = { “name”, “desc” })

public class Role {

@XmlElement

private String name;

@XmlElement

private String desc;



public String getName() {

    return name;

}



public void setName(String name) {

    this.name = name;

}



public String getDesc() {

    return desc;

}



public void setDesc(String desc) {

    this.desc = desc;

}



@Override

public String toString() {

    return "Role [name=" + name + ",desc=" + desc + "]";

}

}




(3)test 



package com.guor.demo.beanToXml;

import org.junit.Test;

public class JaxbTest2 {

@Test

public void showMarshaller() {

    Student student = new Student();

    student.setId(12);

    student.setName("nihao");

    Role role = new Role();

    role.setDesc("管理");

    role.setName("班长");

    student.setRole(role);

    String str = JaxbUtil.converTomXml(student);

    System.out.println(str);



}



@Test

public void showUnMarshaller() {

    String str = "<?xml version =\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" + "<student id =\"12\">"

            + "<name>nihao</name>" + "<role>" + "<desc>管理</desc>" + "<name>班长</name>" + "</role>" + "</student>";

    Student student = JaxbUtil.converyToJavaBean(str, Student.class);

    System.out.println(student);

}

}






### 最后

作为过来人,小编是整理了很多进阶架构视频资料、面试文档以及PDF的学习资料,针对上面一套系统大纲小编也有对应的相关进阶架构视频资料,如果**‘你’**确定好自己未来的道路或者想学习提升自己技术栈、技术知识的小伙伴们**可以[点击这里来获取免费学习资料](https://gitee.com/vip204888/java-p7)提升自己(全套面试文档、PDF、进阶架构视频)**

![](https://www.icode9.com/i/ll/?i=img_convert/3e1212e0ca1b11e610a12d0640e4349e.png)
![](https://www.icode9.com/i/ll/?i=img_convert/6a0cf9071b5bf1a7049f81061feccb11.png)


TF-8\" standalone=\"yes\"?>" + "<student id =\"12\">"

                + "<name>nihao</name>" + "<role>" + "<desc>管理</desc>" + "<name>班长</name>" + "</role>" + "</student>";

        Student student = JaxbUtil.converyToJavaBean(str, Student.class);

        System.out.println(student);

    }

}

最后

作为过来人,小编是整理了很多进阶架构视频资料、面试文档以及PDF的学习资料,针对上面一套系统大纲小编也有对应的相关进阶架构视频资料,如果**‘你’确定好自己未来的道路或者想学习提升自己技术栈、技术知识的小伙伴们可以点击这里来获取免费学习资料提升自己(全套面试文档、PDF、进阶架构视频)**

[外链图片转存中…(img-IjgN1nNL-1628234865678)]
[外链图片转存中…(img-4o6PeBak-1628234865681)]

上一篇:解决在eclipse2021中,用mysql-connector-java-8.0.18.jar不兼容,导致无法访问数据库问题(2021-10-23)


下一篇:JavaBean