主类:
import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.json.JSONArray; import org.json.JSONObject; public class JSONObjectSample { public static void main(String[] args) throws IOException { File file = new File("src/main/java/demo.json"); String content = FileUtils.readFileToString(file); //对基本类型的解析 JSONObject obj = new JSONObject(content); System.out.println("name:" + obj.getString("name")); System.out.println("sex:" + obj.getString("sex")); System.out.println("age" + obj.getInt("age")); System.out.println("is_student" + obj.getBoolean("is_student")); //对数组的解析 JSONArray hobbies = obj.getJSONArray("hobbies"); System.out.println("hobbies:"); for (int i = 0; i < hobbies.length(); i++) { String s = (String) hobbies.get(i); System.out.println(s); } } }