通过JAXBContext实现xml字符串和javaBean互转

public class XmlToBean {

    public static void main(String[] args) {
//        User user = new User(20, "小明明");
//        user.setName("小红");
        User user = new User();
        user.setName("小黄");
        try {
            System.out.println("bean转xml字符串");
            String s = XmlUtil.beanToXmlStr(user);
            System.out.println(s);
            System.out.println("xml转字符串");
            User userTemp = XmlUtil.xmlToBean(s, User.class);
            System.out.println(userTemp);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }

    static class XmlUtil{

        //xml转baen实体
        public static <T> T xmlToBean(String xmlStr,Class<T> load) throws JAXBException {
            JAXBContext jaxbContext = JAXBContext.newInstance(load);
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            T unmarshal = (T)unmarshaller.unmarshal(new StringReader(xmlStr));
            return unmarshal;
        }

        //bean转xml
        public static String beanToXmlStr(Object bean) throws JAXBException {
            JAXBContext jaxbContext = JAXBContext.newInstance(bean.getClass());
            Marshaller marshaller = jaxbContext.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,Boolean.TRUE);

            StringWriter stringWriter = new StringWriter();
            marshaller.marshal(bean,stringWriter);
            return stringWriter.toString();
        }
    }

    @XmlRootElement
    static class User{
        Integer age;
        String name;

        public User(){

        }

        public User(Integer age, String name) {
            this.age = age;
            this.name = name;
        }

        public Integer getAge() {
            return age;
        }

        public void setAge(Integer age) {
            this.age = age;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return "User{" +
                    "age=" + age +
                    ", name='" + name + '\'' +
                    '}';
        }
    }
}

 

发布了17 篇原创文章 · 获赞 8 · 访问量 1万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览