import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class JsonTest { public static void main(String[] args) { String joStr = "{name:\"張三\",age:\"20\"}"; //將json字符串轉化為JSONObject JSONObject jsonObject = JSONObject.fromObject(joStr); //通過getString("")分別取出里面的信息 String name = jsonObject.getString("name"); String age = jsonObject.getString("age"); //輸出 張三 20 System.out.println(name+" "+age); String jaStr = "[{user:{name:\"張三\",age:\"20\"}},{score:{yuwen:\"80\",shuxue:\"90\"}}]"; //將jsonArray字符串轉化為JSONArray JSONArray jsonArray = JSONArray.fromObject(jaStr); //取出數組第一個元素 JSONObject jUser = jsonArray.getJSONObject(0).getJSONObject("user"); //取出第一個元素的信息,並且轉化為JSONObject String name2 = jUser.getString("name"); String age2 = jUser.getString("age"); //輸出 張三 20 System.out.println(name2+" "+age2); //取出數組第二個元素,並且轉化為JSONObject JSONObject jScore = jsonArray.getJSONObject(1).getJSONObject("score"); //取出第二個元素的信息 String yuwen = jScore.getString("yuwen"); String shuxue = jScore.getString("shuxue"); //輸出 80 90 System.out.println(yuwen+" "+shuxue); } }