[Java] 把Object对象转换为XML →→→→→进入此内容的聊天室

来自 , 2020-11-27, 写在 Java, 查看 167 次.
URL http://www.code666.cn/view/67e103b0
  1. import java.beans.BeanInfo;
  2. import java.beans.Introspector;
  3. import java.beans.PropertyDescriptor;
  4. import java.lang.reflect.Method;
  5. import java.util.HashMap;
  6. import java.util.Map;
  7. import com.thoughtworks.xstream.XStream;
  8. import com.thoughtworks.xstream.io.xml.XmlFriendlyReplacer;
  9. import com.thoughtworks.xstream.io.xml.XppDriver;
  10.  
  11. /**
  12.  *Module:       XML_OBJTOXML.java
  13.  *Description:  报文的封装
  14.  *Company:      
  15.  *Author:       pantp
  16.  *Date:         Feb 23, 2012
  17.  */
  18.  
  19. /*
  20.  * 用到的主要知识如下:
  21.  * 1.BeanInfo/Introspector/PropertyDescriptor/Method的使用
  22.  * 2.XStream.jar包相关类及方法的使用
  23.  * 3.javabean
  24.  */
  25.  
  26. /*
  27. 假设报文格式如下:
  28. <user_info>
  29.   <username>testuser</username>
  30.   <password>password</password>
  31. </user_info>
  32.  */
  33.  
  34. /**
  35.  * 定义一个javabean,实际开发中javabean是一个单独的类,这里为了方便就放在了一个类中
  36.  * 实际开发中是先定义报文格式和字段,然后根据定义的报文建立javabean以及属性字段名称
  37.  */
  38. class UserInfo {
  39.         // 此处的属性名称就是最后发送报文中的字段名称
  40.         private String username;
  41.         private String password;
  42.  
  43.         // 这几个类的使用时javabean的属性的类型不能有多种(如:String和int不能共存、但是int和long可以共存),否则后面会报异常
  44.  
  45.         public String getUsername() {
  46.                 return username;
  47.         }
  48.  
  49.         public void setUsername(String username) {
  50.                 this.username = username;
  51.         }
  52.  
  53.         public String getPassword() {
  54.                 return password;
  55.         }
  56.  
  57.         public void setPassword(String password) {
  58.                 this.password = password;
  59.         }
  60. }
  61.  
  62. // =========================================【javabean定义完成】============================================================
  63.  
  64. public class XML_OBJTOXML {
  65.  
  66.         private static Map parameter = new HashMap();
  67.         private static UserInfo userInfo = null;
  68.  
  69.         /**
  70.          * 整合4个方法,提供一个程序的访问的接口
  71.          *
  72.          * @return
  73.          * @throws Exception
  74.          */
  75.         public static String returnXML() throws Exception {
  76.                 /*
  77.                  * 1.放值到map对象中
  78.                  */
  79.                 putValue(parameter);
  80.  
  81.                 /*
  82.                  * 2.把map中的值set到对应Object对象pt中
  83.                  */
  84.                 userInfo = new UserInfo();
  85.                 setBeanProperty(userInfo, parameter);
  86.  
  87.                 /*
  88.                  * 3.采用object to xml 的方式封装xml字符串
  89.                  */
  90.                 String xml = getXML();
  91.  
  92.                 /*
  93.                  * 4.释放资源
  94.                  */
  95.                 close();
  96.  
  97.                 return xml;
  98.         }
  99.  
  100.         /**
  101.          * 放值到Map对象中
  102.          *
  103.          * @param parameter
  104.          */
  105.         private static void putValue(Map parameter) {
  106.                 /*
  107.                  * 实际开发中是查询数据库然后把相应的值put到Map的对象中, 但是此处的键key的值必须要和javabean中的字段名称一模一样,
  108.                  * 多一个空格,大小写不一样的话都不行,这样后面都没有办法把值set到对象中
  109.                  */
  110.                 parameter.put("username", "testuser");
  111.                 parameter.put("password", "123456");
  112.         }
  113.  
  114.         /**
  115.          * 把map中的值set到对应Object对象pt中
  116.          *
  117.          * @param pt
  118.          * @param map
  119.          * @throws Exception
  120.          */
  121.         private static void setBeanProperty(Object obj, Map map) throws Exception {
  122.                 /*
  123.                  * 全面地对类进行查询,返回一个我们可以进行详细研究以发现其属性、方法和事件的BeanInfo对象
  124.                  */
  125.                 BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
  126.                 /*
  127.                  * BeanInfo 返回这些信息的方法如下: getBeanDescriptor():
  128.                  * 返回一个Bean叙词表(BeanDescriptor),包含bean的多方面信息(图标,显示名等)
  129.                  * getPropertyDescriptors(): 返回一属性叙词表,返回的每个元素是一个PropertyDescriptor对象
  130.                  * getMethodDescriptors(): 返回一方法叙词表 ,返回的每个元素是一个MethodDescriptor对象
  131.                  * getEventSetDescriptors(): 返回一事件集叙词表 ,返回的每个元素是一个EventSetDescriptor对象
  132.                  */
  133.                 PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
  134.                 for (int i = 0; i < pds.length; i++) {
  135.                         PropertyDescriptor pd = pds[i];
  136.                         Method methodGetX = pd.getWriteMethod();// getWriteMethod()获得应该用于写入属性值的方法
  137.                         if (map.containsKey(pd.getName())) {// pd.getName()的值即username、password
  138.                                 String value = (map.get(pd.getName())) == null ? "" : map.get(
  139.                                                 pd.getName()).toString();// 取得属性值
  140.                                 if (value != null && value.trim() != "") {
  141.                                         /*
  142.                                          * Object invoke(Object obj, Object... args)
  143.                                          * 对带有指定参数的指定对象调用由此 Method 对象表示的底层方法 obj - 从中调用底层方法的对象 args
  144.                                          * - 用于方法调用的参数 通俗点说就是,调用obj对象中value属性对应的set方法把值放入到obj对象中
  145.                                          */
  146.                                         methodGetX.invoke(obj, new Object[] { value });
  147.                                 }
  148.                         }
  149.                 }
  150.         }
  151.  
  152.         /**
  153.          * 通过XStream类采用object to xml 的方式封装xml字符串
  154.          *
  155.          * @return
  156.          */
  157.         private static String getXML() {
  158.                 XStream xstream = new XStream(new XppDriver(new XmlFriendlyReplacer(
  159.                                 "-_", "_")));// 用此种构造方法是为了去掉报文中下划线占两个字符的问题
  160.  
  161.                 xstream.alias("user_info", UserInfo.class);// 设置别名
  162.                 // addImplicitCollection
  163.  
  164.                 StringBuffer sb = new StringBuffer();
  165.                 sb.append("<?xml version=\"1.0\" encoding=\"gbk\"?>");
  166.                 sb.append("\n");
  167.                 sb.append(xstream.toXML(userInfo));
  168.  
  169.                 return sb.toString();
  170.         }
  171.  
  172.         /**
  173.          * 释放Map对象中的资源
  174.          */
  175.         private static void close() {
  176.                 if (parameter != null && !parameter.isEmpty())
  177.                         parameter.clear();
  178.         }
  179.  
  180.         // =========================================【报文封装完成】============================================================
  181.  
  182.         /**
  183.          * 测试的main方法
  184.          *
  185.          * @param args
  186.          * @throws Exception
  187.          */
  188.         public static void main(String[] args) throws Exception {
  189.                 String result = returnXML();// 实际开发中,可以把这个返回值通过调用webservice接口或者是HTTP接口发送报文到交互的系统中
  190.  
  191.                 // 打印看看结果
  192.                 System.out.println("================================\n");
  193.                 System.out.println(result);
  194.                 System.out.println("\n================================");
  195.         }
  196. }

回复 "把Object对象转换为XML"

这儿你可以回复上面这条便签

captcha