系统交互中,经常会遇到各种形式的参数传递,XML、Map、Json等等,今天整理了一个涵盖各种类型转换的工具类,与大家分享分享!
package org.ccnu.edu.util; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.io.Writer; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import net.sf.json.JsonConfig; import com.sun.org.apache.xml.internal.serialize.OutputFormat; import com.sun.org.apache.xml.internal.serialize.XMLSerializer; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.core.util.QuickWriter; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import com.thoughtworks.xstream.io.xml.PrettyPrintWriter; import com.thoughtworks.xstream.io.xml.XppDriver; /** * describe:bean 、 List<bean>、Map、XML、JSON 相互转换 * * @author Fei.wei * @since JDK 1.6 Date:2015-11-19上午9:30:36 */ @SuppressWarnings("all") public class ObjectConvertUtil<T> { /** * * objectToMap:对象转换为map * * @author Fei.wei * @param t * @return * @throws IntrospectionException * 类属性分析失败 * @throws IllegalArgumentException * @throws IllegalAccessException * @throws InvocationTargetException * 调用属性的setter方法失败 * @since JDK 1.6 Date:2015-11-19 上午9:39:10 */ public static <T> Map<String, String> objectToMap(T t) throws IntrospectionException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { Class<? extends Object> type = t.getClass(); Map<String, String> map = new HashMap<String, String>(); BeanInfo beanInfo = Introspector.getBeanInfo(type); PropertyDescriptor[] propertyDescriptors = beanInfo .getPropertyDescriptors(); for (int i = 0; i < propertyDescriptors.length; i++) { PropertyDescriptor descriptor = propertyDescriptors[i]; String propertyName = descriptor.getName(); if (!propertyName.equals("class")) { Method readMethod = descriptor.getReadMethod(); // 调用get方法取值 invoke第二参数 new Object[]{} 都行,参数为空 Object result = readMethod.invoke(beanInfo, new Object[0]); if (result != null) { map.put(propertyName, (String) result); } else { map.put(propertyName, ""); } } } return map; } /** * * mapToObject:map转换成对象 * * @author Fei.wei * @param type * @param map * @return * @throws IntrospectionException * @throws InstantiationException * @throws IllegalAccessException * @throws IllegalArgumentException * @throws InvocationTargetException * @since JDK 1.6 Date:2015-11-19 上午9:47:42 */ public static <T> T mapToObject(Class<T> type, Map<String, String> map) throws IntrospectionException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { BeanInfo beanInfo = Introspector.getBeanInfo(type); PropertyDescriptor[] propertyDescriptors = beanInfo .getPropertyDescriptors(); // 创建bean对象 T javaBean = type.newInstance(); for (int i = 0; i < propertyDescriptors.length; i++) { PropertyDescriptor descriptor = propertyDescriptors[i]; if (map.containsKey(descriptor.getName())) { // 调用set方法,给属性赋值 Method m = descriptor.getWriteMethod(); m.invoke(javaBean, new Object[] { map.get(descriptor.getName()) }); } } return javaBean; } /** * * listToJson:List<T> 转换成 josn * * @author Fei.wei * @param t * @return * @since JDK 1.6 Date:2015-11-16 下午5:03:56 */ public static<T> String listToJson(T t){ return JSONArray.fromObject(t).toString(); } /** * * jsonToList:json 转换成 List<T> * * @author Fei.wei * @param json * @param type * @return * @since JDK 1.6 Date:2015-11-16 下午5:04:39 */ public static<T> List<T> jsonToList(String json,Class<T> type){ JSONArray jsonArray = JSONArray.fromObject(json); ArrayList<T> list = new ArrayList<T>(); for(Object obj : jsonArray){ list.add(jsonToObject(obj.toString(),type)); } return list; } /** * * objectToJson:bean 转换成json * * @author Fei.wei * @param object * @return * @since JDK 1.6 Date:2015-11-10 下午3:33:21 */ public static<T> String objectToJson(T t){ return JSONObject.fromObject(t).toString(); } /** * * jsonToObject:json转换成bean * * @author Fei.wei * @param json * @param type * @return * @since JDK 1.6 Date:2015-11-10 下午3:33:30 */ @SuppressWarnings("unchecked") public static<T> T jsonToObject(String json,Class<T> type){ JSONObject jsonObject = JSONObject.fromObject(json); /** * java.lang.ClassCastException: net.sf.ezmorph.bean.MorphDynaBean cannot be cast to * 添加JsonConfig,避免抛上面的异常 */ JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setRootClass(type); return (T) JSONObject.toBean(jsonObject,jsonConfig); } /** * * xmlToObj:xml转换成obj * * @author Fei.wei * @param cl * @param xmlString * @return * @throws Exception * @since JDK 1.6 Date:2015-3-26 下午2:34:26 */ public static<T> T xmlToObj(Class<T> cl,String xmlString) throws Exception{ JAXBContext context = JAXBContext.newInstance(cl); ByteArrayInputStream stream = new ByteArrayInputStream(xmlString.getBytes("utf-8")); Unmarshaller um = context.createUnmarshaller(); T p = (T) um.unmarshal(stream); stream.close(); return p; } /** * * objToXML:obj转换成xml * * @author Fei.wei * @param cl * @param obj * @return * @throws Exception * @since JDK 1.6 Date:2015-3-26 下午2:37:08 */ public static<T> String objToXML(Class<T> cl,Object obj) throws Exception{ JAXBContext context = JAXBContext.newInstance(cl); Marshaller m = context.createMarshaller(); ByteArrayOutputStream out = new ByteArrayOutputStream(); XMLSerializer serializer = getXMLSerializer(out); m.marshal(obj, serializer); out.flush(); String xmlString = new String(out.toByteArray(),"utf-8"); return xmlString.substring(xmlString.indexOf("<", 2)); } private static XMLSerializer getXMLSerializer(OutputStream out){ OutputFormat of = new OutputFormat(); of.setCDataElements(new String[]{"^PicUrl","^Url","ns1^foo","ns2^bar","^baz"}); of.setPreserveSpace(true); of.setIndenting(true); XMLSerializer serializer = new XMLSerializer(of); serializer.setOutputByteStream(out); return serializer; } /** * * objToXML:obj转xml,添加 <![CDATA[]]> 标签 * * @author Fei.wei * @param obj * @return * @since JDK 1.6 Date:2015-3-26 下午2:46:11 */ public static String objToXML(Object obj) { xstream.alias("xml", obj.getClass()); return xstream.toXML(obj); } private static XStream xstream = new XStream(new XppDriver() { public HierarchicalStreamWriter createWriter(Writer out) { return new PrettyPrintWriter(out) { boolean cdata = true; @SuppressWarnings("rawtypes") public void startNode(String name, Class clazz) { super.startNode(name, clazz); } protected void writeText(QuickWriter writer, String text) { if (cdata) { writer.write("<![CDATA["); writer.write(text); writer.write("]]>"); } else { writer.write(text); } } }; } }); }