1、JSON数据的解析
//String values={"userId":"123","images":["base641","base642","base643"]}
JSONObject jsStr = JSONObject.fromObject(values);
userId = jsStr.getString("userId"); ` //userId = 123
images = jsStr.getString("images"); //images = ["base641","base642","base643"]
JSONArray jsonArray = new JSONArray(images);
int size = jsonArray.length();
for (int j=0; j<size; j++){
String value = jsonArray.get(j).toString(); //"base641"
}
2、生成JSON
2.1、返回json数据格式
@ResponseBoby
返回数据封装格式
Map<String,String> res = new HashMap<String,String>(2);
res.put("state","false");
res.put("result","成功!");
return res;
2.2、两层json
{"state":"true","result":"[{"userId":"123","score":"100"}]"}
方法一:
Map<String,String> res = new HashMap<String,Object>(2);
JSONArray jsonArr = new JSONArray();
for(int i=0; i<2; i++){
JSONObject em = new JSONObject();
em.put("userId", "123");
em.put("score","100");
jsonArr.put(em);
}
res.put("state", "true");
res.put("result", jsonArr.toString());
方法二:
Map<String,Object> res = new HashMap<String,Object>(2);
Object[] resultList = new Object[2];
for (int i=0; i<idList.length;i++){
Map<String,String> result = new HashMap<String,String>(2);
result.put("userId","123");
result.put("score", "100");
resultList[i] = result;
}
System.out.println("reslut:"+Arrays.toString(resultList));
res.put("state", "true");
res.put("result", resultList);