Json转java对象和List集合
Posted Henu丶雨巷
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Json转java对象和List集合相关的知识,希望对你有一定的参考价值。
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\"}]"; @SuppressWarnings("rawtypes") List list = (List)json2ObjectList(json, aaaa.class); @SuppressWarnings("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); }
以上是关于Json转java对象和List集合的主要内容,如果未能解决你的问题,请参考以下文章
一个java对象内包含一个对象集合 用json-lib框架怎么转换成JSON数据格式
java json数据转List对象的集合-----阿里巴巴插件---及原生json---JSON 与 对象 集合 之间的转换 JSON字符串和java对象的互转json-lib