JSONObject:是一个json对象,就是一个键对应一个值,使用的是大括号{ },即:{key:value};
JSONArray: json数组,使用中括号[ ],只不过数组里面的项也是json键值对格式的;
也就是说 Json对象中添加的是键值对,JSONArray中添加的是Json对象:
JSONObject json = new JSONObject();
JSONArray jsonArray = new JSONArray();
json.put("key","value");//JSONObject对象中添加键值对
jsonArray.add(json); //将JSONObject对象添加到Json数组中
1、下面是Java对JSONObject的解析遍历并保存到数据库:
JSONObject json = JSONObject.fromObject(getPara("data"));
Record user = Db.findFirst(" select * from sys_user where phone = ? and status = 1 ", json.get("phone"));
if( user == null ){
user = new Record();
}
user.set("namezh", json.get("namezh"));
user.set("uname", json.get("phone"));
user.set("phone", json.get("phone"));
user.set("drivernum", json.get("drivernum"));
if(user.get("id") != null){
Db.update("sys_user", user);
}else{
Db.save("sys_user", user);
}
2、下面是Java对JSONArray的解析遍历转换成List:
这里的json.get("cars")这样解释:json是1中的json,cars是封装在json中的json数组
JSONArray jsonarray = JSONArray.fromObject(json.get("cars").toString());
Iterator<Object> it = jsonarray.iterator();
List<Record> temp_list = new ArrayList<Record>();
while(it.hasNext()){
JSONObject ob = (JSONObject) it.next();
Record r = new Record();
if(ob.get("guid") != null){
r.set("guid", ob.get("guid"));
}
if(ob.get("namezh") != null){
r.set("namezh", ob.get("namezh"));
}
if(ob.get("drivingnum") != null){
r.set("drivingnum", ob.get("drivingnum"));
}
if(ob.get("oqc") != null){
r.set("oqc", ob.get("oqc"));
}
if(ob.get("carnum") != null){
r.set("carnum", ob.get("carnum"));
}
if(ob.get("province") != null){
r.set("province", ob.get("province"));
}
if(ob.get("city") != null){
r.set("city", ob.get("city"));
}
if(ob.get("county") != null){
r.set("county", ob.get("county"));
}
if(ob.get("cartype") != null){
r.set("cartype", ob.get("cartype"));
}
if(ob.get("carlong") != null){
r.set("carlong", ob.get("carlong"));
}
if(ob.get("carload") != null){
r.set("carload", ob.get("carload"));
}
if(ob.get("enginenum") != null){
r.set("enginenum", ob.get("enginenum"));
}
if(r != null){
temp_list.add(r);
}
}