一:利用alibaba.fastjson解析JSONObject、JSONArray
package com.test1;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
public class TestJsonArray {
public static void main(String[] args) {
// json字符串-简单对象型
final String JSON_OBJ_STR = "{\"studentName\":\"lily\",\"studentAge\":12}";
// json字符串-数组类型
final String JSON_ARRAY_STR = "[{\"studentName\":\"lily\",\"studentAge\":12},{\"studentName\":\"lucy\",\"studentAge\":15}]";
testJSONStrToJSONArray1(JSON_ARRAY_STR);
testJSONStrToJSONObject(JSON_OBJ_STR);
}
/**
* json字符串-数组类型与JSONArray之间的转换
*/
public static void testJSONStrToJSONArray1(String JSON_ARRAY_STR) {
JSONArray jsonArray = JSON.parseArray(JSON_ARRAY_STR);
// JSONArray jsonArray1 =JSONArray.parseArray(JSON_ARRAY_STR);//因为JSONArray继承了JSON,所以这样也是可以的
// 遍历方式1
int size = jsonArray.size();
for (int i = 0; i < size; i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
System.out.println(jsonObject.getString("studentName") + ":" + jsonObject.getInteger("studentAge"));
}
// 遍历方式2
for (Object obj : jsonArray) {
JSONObject jsonObject = (JSONObject) obj;
System.out.println(jsonObject.getString("studentName") + ":" + jsonObject.getInteger("studentAge"));
}
}
/**
* json字符串-简单对象型与JSONObject之间的转换
*/
public static void testJSONStrToJSONObject(String JSON_OBJ_STR) {
JSONObject jsonObject = JSON.parseObject(JSON_OBJ_STR);
//JSONObject jsonObject1 = JSONObject.parseObject(JSON_OBJ_STR); //因为JSONObject继承了JSON,所以这样也是可以的
System.out.println(jsonObject.getString("studentName") + ":" + jsonObject.getInteger("studentAge"));
}
}
二:利用json.JSONObject解析JSONObject
package com.test1;
import org.json.JSONException;
import org.json.JSONObject;
public class TestJsonObject {
public static void main(String[] args) throws JSONException {
//记得转义
String jsonStr="{\"studentName\":\"zhangsanfeng\",\"age\":18,\"school\":\"武当山大学\"}";
JSONObject jsonObj = new JSONObject(jsonStr);
int age = jsonObj.getInt("age");
String request = (String) jsonObj.get("request");
System.out.println(age);
System.out.println(request);
}
}