1>java对象转json ,使用JSONArray

1 UserInfo user = new UserInfo(1001,"张三");
2 JSONArray jsonArray = JSONArray.fromObject(user);  
3 System.out.println( jsonArray ); 

 2>Map转换成json, 使用JSONObject

1 Map<String, Object> map = new HashMap<String, Object>();
2 map.put("userId", 1001);
3 map.put("userName", "张三");
4 map.put("userSex", "男");
5 JSONObject jsonObject = JSONObject.fromObject(map);
6 System.out.println(jsonObject);

3>List转换成JSON数据,使用JSONArray

1 List<UserInfo> list = new ArrayList<UserInfo>();
2 UserInfo user = new UserInfo(1001, "张三");
3 list.add(user);
4 list.add(user);
5 list.add(user);
6 JSONArray jsonArray = JSONArray.fromObject(list);
7 System.out.println(jsonArray);

4>将数组转换为JSON,使用JSONArray

1 String[] arr = {"asd","dfgd","asd","234"};
2 JSONArray jsonarray = JSONArray.fromObject(arr);
3 System.out.println(jsonarray);

 注:Object转jsonString

 

1 public static String convertObjectToJson(Object obj) {
2         String json = JSONArray.toJSONString(obj);
3         return json;
4     }

 

posted on 2016-07-18 16:20  筱筱鹿丸  阅读(341)  评论(0编辑  收藏  举报