java使用commons-betwixt 实现bean与xml互转

项目下载地址http://download.csdn.net/detail/afgasdg/4825666

项目所需的jar包:

一、XML2BeanUtils.java工具类如下:

更多学习资料请访问 https://www.itkc8.com

[java] view plaincopy在CODE上查看代码片派生到我的代码片

  1. package com.viathink.core.utils;  
  2.   
  3. import java.beans.IntrospectionException;  
  4. import java.io.IOException;  
  5. import java.io.StringReader;  
  6. import java.io.StringWriter;  
  7.   
  8. import org.apache.commons.betwixt.BindingConfiguration;  
  9. import org.apache.commons.betwixt.IntrospectionConfiguration;  
  10. import org.apache.commons.betwixt.expression.Context;  
  11. import org.apache.commons.betwixt.io.BeanReader;  
  12. import org.apache.commons.betwixt.io.BeanWriter;  
  13. import org.apache.commons.betwixt.strategy.DecapitalizeNameMapper;  
  14. import org.apache.commons.betwixt.strategy.DefaultObjectStringConverter;  
  15. import org.apache.commons.betwixt.strategy.HyphenatedNameMapper;  
  16. import org.xml.sax.SAXException;  
  17.   
  18. /** 
  19.  * Xml文件与javaBean对象互转工具类 
  20.  * @author LiuJunGuang 
  21.  * @date 2012-11-21下午1:38:56 
  22.  */  
  23. public class XML2BeanUtils {  
  24.     private static final String xmlHead = "<?xml version='1.0' ?>";  
  25.   
  26.     /** 
  27.      * 将javaBean对象转换成xml文件,对于没有设置的属性将不会生成xml标签 
  28.      * @author LiuJunGuang 
  29.      * @param obj 待转换的javabean对象 
  30.      * @return String 转换后的xml 字符串 
  31.      * @throws IntrospectionException  
  32.      * @throws SAXException  
  33.      * @throws IOException  
  34.      * @date 2012-11-21下午1:38:53 
  35.      */  
  36.     public static String bean2XmlString(Object obj) throws IOException, SAXException, IntrospectionException {  
  37.         if (obj == null)  
  38.             throw new IllegalArgumentException("给定的参数不能为null!");  
  39.         StringWriter sw = new StringWriter();  
  40.         sw.write(xmlHead);// 写xml文件头  
  41.         BeanWriter writer = new BeanWriter(sw);  
  42.         IntrospectionConfiguration config = writer.getXMLIntrospector().getConfiguration();  
  43.         BindingConfiguration bc = writer.getBindingConfiguration();  
  44.         bc.setObjectStringConverter(new DateConverter());  
  45.         bc.setMapIDs(false);  
  46.         config.setAttributesForPrimitives(false);  
  47.         config.setAttributeNameMapper(new HyphenatedNameMapper());  
  48.         config.setElementNameMapper(new DecapitalizeNameMapper());  
  49.         writer.enablePrettyPrint();  
  50.         writer.write(obj.getClass().getSimpleName(), obj);  
  51.         writer.close();  
  52.         return sw.toString();  
  53.     }  
  54.   
  55.     /** 
  56.      * 将xml文件转换成相应的javabean对象,对于List,Map,Array转换时需要在需要保证Bean类中有单个添加方法</br> 
  57.      * <p><blockquote><pre> 
  58.      * 例如:List<{@link String}> userNameList --> addUserNameList(String username) 
  59.      *      String[] items            --> addItems(String item) 
  60.      *      Map<String,User> userMap               --> addUserMap(String key,User user) 
  61.      * </pre></blockquote></p> 
  62.      * 注意:<br> 
  63.      *     目前还没有找到好的方法解决Map与Map嵌套,List与List等嵌套的问题,使用时应当避免以上几种情况。 
  64.      * @author LiuJunGuang 
  65.      * @param beanClass 待转换的javabean字节码 
  66.      * @param xmlFile xml文件字符串 
  67.      * @return 转换后的对象 
  68.      * @throws IntrospectionException  
  69.      * @throws SAXException  
  70.      * @throws IOException  
  71.      * @date 2012-11-21下午1:40:14 
  72.      */  
  73.     @SuppressWarnings("unchecked")  
  74.     public static <T> T xmlSring2Bean(Class<T> beanClass, String xmlFile) throws IntrospectionException, IOException,  
  75.             SAXException {  
  76.         if (beanClass == null || xmlFile == null || xmlFile.isEmpty())  
  77.             throw new IllegalArgumentException("给定的参数不能为null!");  
  78.         StringReader xmlReader = new StringReader(xmlFile);  
  79.         BeanReader reader = new BeanReader();  
  80.         reader.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false);  
  81.         BindingConfiguration bc = reader.getBindingConfiguration();  
  82.         bc.setObjectStringConverter(new DateConverter());  
  83.         bc.setMapIDs(false);  
  84.         T obj = null;  
  85.         reader.registerBeanClass(beanClass.getSimpleName(), beanClass);  
  86.         obj = (T) reader.parse(xmlReader);  
  87.         xmlReader.close();  
  88.         return obj;  
  89.     }  
  90.   
  91.     /** 
  92.      * 日期转换,主要是解决日期为null或者空字符串解析报错问题 
  93.      * @author LiuJunGuang 
  94.      * @date 2013年12月31日下午6:56:49 
  95.      */  
  96.     private static class DateConverter extends DefaultObjectStringConverter {  
  97.         private static final long serialVersionUID = -197858851188189916L;  
  98.   
  99.         @Override  
  100.         @SuppressWarnings("rawtypes")  
  101.         public String objectToString(Object object, Class type, String flavour, Context context) {  
  102.             return super.objectToString(object, type, flavour, context);  
  103.         }  
  104.   
  105.         @Override  
  106.         @SuppressWarnings("rawtypes")  
  107.         public Object stringToObject(String string, Class type, String flavour, Context context) {  
  108.             if (string == null || "".equals(string))  
  109.                 return null;  
  110.             return super.stringToObject(string, type, flavour, context);  
  111.         }  
  112.   
  113.     }  
  114. }  

 

 

 

 

    二、简单的javabean对象:

 

 

[java] view plaincopy在CODE上查看代码片派生到我的代码片

  1. package com.aimilin;  
  2.   
  3. public class PersonBean {  
  4.   
  5.     private String name;  
  6.     private int age;  
  7.   
  8.     public PersonBean() {  
  9.     }  
  10.   
  11.     public PersonBean(String name, int age) {  
  12.         this.name = name;  
  13.         this.age = age;  
  14.     }  
  15.   
  16.     public String getName() {  
  17.         return name;  
  18.     }  
  19.   
  20.     public void setName(String name) {  
  21.         this.name = name;  
  22.     }  
  23.   
  24.     public int getAge() {  
  25.         return age;  
  26.     }  
  27.   
  28.     public void setAge(int age) {  
  29.         this.age = age;  
  30.     }  
  31.   
  32.     @Override  
  33.     public String toString() {  
  34.         return "PersonBean[name='" + name + "',age='" + age + "']";  
  35.     }  
  36. }  

[java] view plaincopy在CODE上查看代码片派生到我的代码片

  1. package com.aimilin;  
  2.   
  3. import java.io.Serializable;  
  4. import java.util.Arrays;  
  5. import java.util.HashMap;  
  6. import java.util.LinkedList;  
  7. import java.util.List;  
  8. import java.util.Map;  
  9.   
  10. public class User implements Serializable {  
  11.     private static final long serialVersionUID = 1354973253595584043L;  
  12.     private String userName;  
  13.     private int age;  
  14.     private PersonBean person;  
  15.     private List<String> hobbyList;  
  16.     private Map<String, PersonBean> personMap;  
  17.     private String[] hobbyArray;  
  18.   
  19.     /** 
  20.      * 添加map类型属性的方法 
  21.      * @param key 
  22.      * @param person 
  23.      * @date 2012-11-29下午1:01:06 
  24.      */  
  25.     public void addPersonMap(String key, PersonBean person) {  
  26.         if (personMap == null) {  
  27.             personMap = new HashMap<String, PersonBean>();  
  28.         }  
  29.         personMap.put(key, person);  
  30.     }  
  31.   
  32.     /** 
  33.      * 添加list类型的方法 
  34.      * @param hobby 
  35.      * @date 2012-11-29下午1:01:07 
  36.      */  
  37.     public void addHobbyList(String hobby) {  
  38.         if (hobbyList == null) {  
  39.             hobbyList = new LinkedList<String>();  
  40.         }  
  41.         hobbyList.add(hobby);  
  42.     }  
  43.   
  44.     /** 
  45.      * 添加数组类型的方法 
  46.      * @param hobby 
  47.      * @date 2012-11-29下午1:01:09 
  48.      */  
  49.     public void addHobbyArray(String hobby) {  
  50.         hobbyArray = StringUtils.addStringToArray(hobbyArray, hobby);  
  51.     }  
  52.   
  53.     public String getUserName() {  
  54.         return userName;  
  55.     }  
  56.   
  57.     public void setUserName(String userName) {  
  58.         this.userName = userName;  
  59.     }  
  60.   
  61.     public int getAge() {  
  62.         return age;  
  63.     }  
  64.   
  65.     public void setAge(int age) {  
  66.         this.age = age;  
  67.     }  
  68.   
  69.     public User() {  
  70.         super();  
  71.     }  
  72.   
  73.     public PersonBean getPerson() {  
  74.         return person;  
  75.     }  
  76.   
  77.     public void setPerson(PersonBean person) {  
  78.         this.person = person;  
  79.     }  
  80.   
  81.     public List<String> getHobbyList() {  
  82.         return hobbyList;  
  83.     }  
  84.   
  85.     public void setHobbyList(List<String> hobbyList) {  
  86.         this.hobbyList = hobbyList;  
  87.     }  
  88.   
  89.     public Map<String, PersonBean> getPersonMap() {  
  90.         return personMap;  
  91.     }  
  92.   
  93.     public void setPersonMap(Map<String, PersonBean> personMap) {  
  94.         this.personMap = personMap;  
  95.     }  
  96.   
  97.     public String[] getHobbyArray() {  
  98.         return hobbyArray;  
  99.     }  
  100.   
  101.     public void setHobbyArray(String[] hobbyArray) {  
  102.         this.hobbyArray = hobbyArray;  
  103.     }  
  104.   
  105.     @Override  
  106.     public String toString() {  
  107.         return "User [userName=" + userName + ", age=" + age + ", person=" + person + ", hobbyList=" + hobbyList  
  108.                 + ", personMap=" + personMap + ", hobbyArray=" + Arrays.toString(hobbyArray) + "]";  
  109.     }  
  110.   
  111. }  


测试类:

 

 

[java] view plaincopy在CODE上查看代码片派生到我的代码片

  1. package com.aimilin;  
  2.   
  3. import java.util.Arrays;  
  4. import java.util.HashMap;  
  5. import java.util.Map;  
  6.   
  7. import org.junit.Test;  
  8.   
  9. public class XML2BeanUtilsTest {  
  10.     @Test  
  11.     //测试简单属性  
  12.     public void testPsersonBean() throws Exception {  
  13.         String xmlString = XML2BeanUtils.bean2XmlString(createPerson());  
  14.         System.out.println(xmlString);  
  15.         PersonBean person = XML2BeanUtils.xmlSring2Bean(PersonBean.class, xmlString);  
  16.         System.out.println(person);  
  17.     }  
  18.   
  19.     @Test  
  20.     //测试复杂属性  
  21.     public void testUser() throws Exception {  
  22.         String xmlString = XML2BeanUtils.bean2XmlString(createUser());  
  23.         System.out.println(xmlString);  
  24.         User user = XML2BeanUtils.xmlSring2Bean(User.class, xmlString);  
  25.         System.out.println(user);  
  26.     }  
  27.   
  28.     public PersonBean createPerson() {  
  29.         return new PersonBean("name"23);  
  30.     }  
  31.   
  32.     //创建复杂的用户对象  
  33.     public User createUser() {  
  34.         User user = new User();  
  35.         user.setAge(18);  
  36.         user.setUserName("张三");  
  37.         user.setHobbyArray(new String[] { "篮球""足球""乒乓球""羽毛球" });  
  38.         user.setHobbyList(Arrays.asList(new String[] { "游泳""蛙游""蝶泳""自由泳""狗刨" }));  
  39.         user.setPerson(createPerson());  
  40.         Map<String, PersonBean> personMap = new HashMap<String, PersonBean>();  
  41.         for (int i = 0; i < 5; i++) {  
  42.             personMap.put("person" + i, new PersonBean("person" + i, i));  
  43.         }  
  44.         user.setPersonMap(personMap);  
  45.         return user;  
  46.     }  
  47. }  

 


结果:testPsersonBean运行结果:

 

 

 

[html] view plaincopy在CODE上查看代码片派生到我的代码片

  1. <?xml version='1.0' ?>  
  2.   <PersonBean>  
  3.     <age>23</age>  
  4.     <name>name</name>  
  5.   </PersonBean>  

PersonBean[name='name',age='23']

 

testUser运行结果:

 

[html] view plaincopy在CODE上查看代码片派生到我的代码片

  1. <?xml version='1.0' ?>  
  2.   <User>  
  3.     <age>18</age>  
  4.     <hobbyArray>  
  5.       <hobbyArray>篮球</hobbyArray>  
  6.       <hobbyArray>足球</hobbyArray>  
  7.       <hobbyArray>乒乓球</hobbyArray>  
  8.       <hobbyArray>羽毛球</hobbyArray>  
  9.     </hobbyArray>  
  10.     <hobbyList>  
  11.       <hobbyList>游泳</hobbyList>  
  12.       <hobbyList>蛙游</hobbyList>  
  13.       <hobbyList>蝶泳</hobbyList>  
  14.       <hobbyList>自由泳</hobbyList>  
  15.       <hobbyList>狗刨</hobbyList>  
  16.     </hobbyList>  
  17.     <person>  
  18.       <age>23</age>  
  19.       <name>name</name>  
  20.     </person>  
  21.     <personMap>  
  22.       <entry>  
  23.         <key>person3</key>  
  24.         <value>  
  25.           <age>3</age>  
  26.           <name>person3</name>  
  27.         </value>  
  28.       </entry>  
  29.       <entry>  
  30.         <key>person4</key>  
  31.         <value>  
  32.           <age>4</age>  
  33.           <name>person4</name>  
  34.         </value>  
  35.       </entry>  
  36.       <entry>  
  37.         <key>person1</key>  
  38.         <value>  
  39.           <age>1</age>  
  40.           <name>person1</name>  
  41.         </value>  
  42.       </entry>  
  43.       <entry>  
  44.         <key>person2</key>  
  45.         <value>  
  46.           <age>2</age>  
  47.           <name>person2</name>  
  48.         </value>  
  49.       </entry>  
  50.       <entry>  
  51.         <key>person0</key>  
  52.         <value>  
  53.           <age>0</age>  
  54.           <name>person0</name>  
  55.         </value>  
  56.       </entry>  
  57.     </personMap>  
  58.     <userName>张三</userName>  
  59.   </User>  


User [userName=张三, age=18, person=PersonBean[name='name',age='23'], hobbyList=[游泳, 蛙游, 蝶泳, 自由泳, 狗刨], personMap={person3=PersonBean[name='person3',age='3'], person4=PersonBean[name='person4',age='4'], person1=PersonBean[name='person1',age='1'], person2=PersonBean[name='person2',age='2'], person0=PersonBean[name='person0',age='0']}, hobbyArray=[篮球, 足球, 乒乓球, 羽毛球]]

更多学习资料请访问 https://www.itkc8.com

 

 

项目下载地址http://download.csdn.net/detail/afgasdg/4825666

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值