public static void main(String[] args) { // 转换对象 String strJson ="{/"basemenu_id/":/"1/",/"basemenu_name/":/"aaaaaa/",/"basemenu_order/":/"2/"}"; aaaa jb = (aaaa)json2Object(strJson,aaaa.class);//javabean 要加 ".class" System.out.print("json转对象"+jb.getBasemenu_id()+","+jb.getBasemenu_name()+","+jb.getBasemenu_order()+"/n"); //转list String json="[{/"basemenu_id/":/"1/",/"basemenu_name/":/"aaaaaa/",/"basemenu_order/":/"2/"}," + "{/"basemenu_id/":/"2/",/"basemenu_name/":/"cccccc/",/"basemenu_order/":/"3/"}," + "{/"basemenu_id/":/"3/",/"basemenu_name/":/"dddddd/",/"basemenu_order/":/"4/"}," + "{/"basemenu_id/":/"4/",/"basemenu_name/":/"bbbbbb/",/"basemenu_order/":/"5/"}," + "{/"basemenu_id/":/"5/",/"basemenu_name/":/"eeeeee/",/"basemenu_order/":/"6/"}," + "{/"basemenu_id/":/"6/",/"basemenu_name/":/"rrrrrr/",/"basemenu_order/":/"7/"}," + "{/"basemenu_id/":/"7/",/"basemenu_name/":/"tttttt/",/"basemenu_order/":/"8/"}," + "{/"basemenu_id/":/"8/",/"basemenu_name/":/"uuuuuu/",/"basemenu_order/":/"9/"}," + "{/"basemenu_id/":/"9/",/"basemenu_name/":/"oooooo/",/"basemenu_order/":/"10/"}," + "{/"basemenu_id/":/"10/",/"basemenu_name/":/"llllll/",/"basemenu_order/":/"11/"}]"; [email protected]("rawtypes") List list = (List)json2ObjectList(json, aaaa.class); [email protected]("rawtypes") Iterator it = list.iterator(); System.out.print("集合循环/n"); while(it.hasNext()){ aaaa p = (aaaa)it.next(); System.out.print(p.getBasemenu_id()+","+p.getBasemenu_name()+","+p.getBasemenu_order()+"/n"); } } //单个对象 public static Object json2Object(String strJson, @SuppressWarnings("rawtypes") Class beanClass) { return JSONObject.toBean(JSONObject.fromObject(strJson), beanClass); } //返回 list 对象数组 字符串JSON要添加[] public static Object json2ObjectList(String strJson, @SuppressWarnings("rawtypes")Class beanClass) { return JSONArray.toCollection(JSONArray.fromObject(strJson), beanClass); }
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/16043.html