先給大家介紹下地圖和對象互相轉換的代碼。
具體代碼如所示:
/ ** *使用org.apache.commons.beanutils進行轉換 */ a class a {public static object maptoobject(map <string,object> map> apr> class <?> beanclass)拋出異常{if(map = = = = = = = = = = = null)return null;對象obj = beanclass.newinstance(); org.apache.commons.beanutils.beanutils.populate(obj,map);返回obj; } public靜態映射<? > objectTomap(object obj){if(obj == null)return null;返回新的org.apache.commons.beanutils.beanmap(obj); }} / ** *使用in Introspector進行轉換 * /類B {public static Object maptOObject(Map <string,Object> Map,class <?> beanClass)拋出異常{if(map == null)return null;對象obj = beanclass.newinstance(); beaninfo beaninfo = Introspector.getBeanInfo(obj.getClass()); propertyDescriptor [] propertyDescriptors = beaninfo.getPropertyDescriptors(); for(propertyDescriptor屬性:propertyDescriptors){method setter = property.getWriteMethod(); if(setter!= null){setter.invoke(obj,map.get(property.getName())); }}返回obj; } public static映射<字符串,object> objectTomap(object obj)引發異常{if(obj == null)return null; MAP <String,Object> map = new Hashmap <String,Object>(); beaninfo beaninfo = Introspector.getBeanInfo(obj.getClass()); propertyDescriptor [] propertyDescriptors = beaninfo.getPropertyDescriptors(); for(propertyDescriptor屬性:propertyDescriptors){string key = property.getName(); if(key.com.comparetoignorecase(“ class”)== 0){繼續; }方法getter = property.getReadMethod();對象值= getter! = null? getter.invoke(obj):null; map.put(鍵,值); }返回地圖; }} / ** *使用反射進行轉換 * / class c {public static對象maptoobject(map <string,object> map,class <?> beanclass)拋出異常{if(ap == == null)return null;對象obj = beanclass.newinstance(); field [] fields = obj.getClass()。 getDeclaredFields(); for(字段:字段){int mod = field.getModifiers(); if(modifier.isstatic(mod)|| modifier.fisfinal(mod)){繼續; } field.setAccessible(true); field.set(obj,map.get(field.getName())); }返回obj; } public靜態映射<string,object> objectTomap(object obj)引發異常{if(obj == null){return null; } map <字符串,object> map = new Hashmap <String,Object>(); field [] ecledfields = obj.getClass()。 getDeclaredFields(); for(field field:evelared fields){field.setAccessible(true); map.put(field.getName(),field.get(obj)); }返回地圖; } <p>} </p> <p> </p> <p>來自:http://www.open-open.com/code/code/view/1423280939826 </p>下面給大家介紹地圖和json的互相轉換
第一段代碼
地圖<字符串,對象> map =新哈希瑪普<字符串,object>(); map.put(“方法”,“ json”); map.put(“ param”,null); map.put(“ time”,“ 2015-01-23 10:54:55”)10:54:55“)
第二段代碼
public static void readjson2map(string json){objectMapper objectmapper = new ObjectMapper(); try {//將json字符串轉成映射結合解析出來,並打印,圖(這里以解析成映射)映射<string,map <string,object >> maps >> maps => maps => maps = appermapper.read.readvalue(json,map.class; system.out.outnize; system.outnize; maps.keyset(); iterator <Iterator <Iter = key.iterator(); while(iter.hasnext()){字符串field = iter.next(); system.out.ut.println(field +“:” + maps.get(field(field)) {e.printstacktrace();} catch(ioexception e){e.printstacktrace();}} readjson2map(json);以上內容是小編給大家介紹的java代碼實現映射和對象互轉及地圖和json的互轉的相關知識,希望對大家有所幫助,如果大家想了解更多資訊敬請關注武林網網站