系统交互中,经常会遇到各种形式的参数传递,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); } } }; } }); }
相关推荐
<ref bean="mappingJacksonHttpMessageConverter" /> <ref bean="stringHttpMessageConverter" /> </list> </property> </bean> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework...
public List<Sys_user> selectByPageCondition(Map<String, Object> map) { int pageNo = Integer.parseInt(map.get("pageNo").toString()); int pageSize = Integer.parseInt(map.get("pageSize").toString()); ...
public Map<String, Object> handleAjaxRequest(@RequestParam Map<String, String> params) { // 处理业务逻辑 List<Movie> movies = movieDao.getMovies(params); return Collections.singletonMap("movies", ...
通过fastjson实现了JavaBean,list<JavaBean>,MAP,list<String>等格式与json格式之间的转换,已经附带fastjson的包,包的版本为fastjson-1.1.36.jar
List<Person> people = new ArrayList<>(); // 添加Person对象到people... JSONArray jsonArray = JSONArray.fromObject(people); List<Person> deserializedPeople = (List<Person>) JSONArray.toCollection...
List<Person> people = new ArrayList<>(); people.add(person); JSONArray jsonArray = JSONArray.fromObject(people); System.out.println(jsonArray.toString()); ``` 同样,从JSON数组反序列化到List: ```...
Map<String, Object> data = new HashMap<>(); data.put("name", "John"); data.put("age", 30); data.put("city", "New York"); JsonConfig jsonConfig = new JsonConfig(); JSONObject jsonData = JSONObject....
<bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"/> <bean class="org.springframework.web.servlet.view.xml.MarshallingView"> <constructor-arg> <bean class="org.spring...
Map<String, String> responseMap = new HashMap<>(); responseMap.put("message", "Hello from JSON"); return responseMap; } } ``` 这个例子展示了如何通过不同的视图解析器,根据请求的 URL 返回 JSP、...
在这个转换过程中,它可能用于辅助处理数据结构,如Map和List,这些在JSON和XML中都常见。 2. **xom-1.2.3.jar**: eXtensible Object Modeling (XOM) 是一个用于XML处理的Java库,它提供了一个简单、高性能、类型...
`Dealer`类的实例可以通过`bean`转换器自动映射到JavaScript对象,而`Monitor`类的方法如`setDealers`和`setDealersMap`允许接收`List<Dealer>`和`Map<String, Dealer>`类型的参数。 接下来,让我们看看具体的Java...
List<JsonBean2> list = new ArrayList<>(); JsonBean2 jb1 = new JsonBean2(); jb1.setCol(1); jb1.setRow(1); jb1.setValue("xx"); list.add(jb1); // add more beans to the list if needed // Assuming...
DWR(Direct Web Remoting)是一种简化JavaScript调用Java方法的技术,它允许Web应用程序的客户端直接访问服务器端的Java对象,从而实现Ajax功能而无需编写复杂的XML或JSON序列化代码。本文将通过一个实战案例,详细...
private static Map<Integer, List<Person>> persons = new HashMap<>(); // 初始化数据 static { for (int i = 0; i < 10; i++) { Org org = new Org(); org.setId(i); org.setName("省份" + i); orgs.put...
同时,`json-lib`还提供了方法将Java对象如Map、List等直接转化为JSON格式。 总的来说,Java与JSON的交互是通过如`json-lib`这样的库来实现的,这些库利用其他Apache Commons库提供的功能,使得在Java中处理JSON变...
“json-lib”是一个开源的Java库,它提供了多种Java集合和XML与JSON之间的转换,包括List、Map、Bean等对象。这个库支持JDK 1.4及以上版本,因此在广泛的Java项目中都有应用。 **json-lib的主要功能:** 1. **JSON...
List<String> list = new ArrayList<>(); list.add("Hello"); list.add("Say"); list.add("张三"); return list; } ``` 客户端调用: ```javascript $("#btn2").click(function () { HelloWorld.getMsg({ ...
本文将深入探讨如何使用JSON-lib库实现JSON与Java Bean、Map、List等数据结构之间的相互转换。 #### JSON-lib简介及安装 JSON-lib是早期非常流行的用于处理JSON的Java库之一。它提供了强大的功能,能够将JSON字符...
PageInfo<User> pageInfo = new PageInfo<>(users); ``` 这里的 `pageNum` 和 `pageSize` 分别表示当前页码和每页大小。 5. **Controller 层返回**:在 Controller 层,我们将分页信息和数据一起返回给前端。例如...
private Map<String, String> converter; private List<Person> defaultShareUsers; @Getter @Setter public static class AuthInfo { private String username; private String password; } } ``` 绑定...