首先引入相关jar包,
假设有一个实体类User
public class User{ private int id; private String name; }
然后通过fastJson进行类型转换
public static void main(String[] args){ String userString = "{"id":1,"name","lz"}"; JSONObject userJson = JSONObject.parseObject(userString); User user = JSON.toJavaObject(userJson,User.class); }
假设数据格式如下:
list 数据格式如下: { "roleid":23, "username":"admin", "data":[ {"autoid":1,"p1":true,"p2":false,"p3":true,......,"p80":false}, {"autoid":2,"p1":true,"p2":false,"p3":true,......,"p80":false}, ......... ] }
那么取数代码如下:
String jsonstr = JSON.toJSONString(list); JSONObject jobj = JSONObject.parseObject(jsonstr); String autoid = jobj.getString("autoid"); //获取 autoid 变量 String username = jobj.getString("username"); //获取 username 变量 JSONArray jary = jobj.getJSONArray("data"); //获取 data 数组 if(jary!=null){ if(jary.size()>0){ for(int i=0;i<jary.size();i++){ //遍历 data 数据 JSONObject jo = jary.getJSONObject(i); TempRolePri trp = JSON.toJavaObject(jo,TempRolePri.class); trp.save(); } } }
json数组转List<Map<String,Object>>,如有以下的json格式:
[ {"autoid":1,"canchange":true}, {"autoid":2,"canchange":true}, .......... ]
需要把它转为一个List队列,代码如下:
String jsonstr = JSON.toJSONString(list); List<Map<String,Object>> lsmap = JSONArray.parseObject(jsonstr,List.class); for(Map<String,Object> map:lsmap){ String autoid = map.get("autoid").toString(); boolean canchange = Boolean.parseBoolean(map.get("canchange").toString()); 。。。。。。。。。 }