- 不支持 JavaBean 反解析
- 无日期格式,只好把日期类型定义成字符串类型,需要时转换
解析给定的 json 格式的数据,实现源代码(op.json在java工程src( /main/java )下)
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.json.JSONArray;
import org.json.JSONObject;
public class ReadJSONExample {
public static void main(String[] args) throws IOException {
File file = new File(ReadJSONExample.class.getResource("/op.json").getFile());
String content = FileUtils.readFileToString(file);
JSONObject jon = new JSONObject(content);
// 增强程序的健壮性,使用 isNull()方法加个判断
if (!jon.isNull("name")) {
System.out.println("姓名是:" + jon.getString("name"));
}
System.out.println("年龄是:" + jon.getDouble("age"));
JSONArray jay = jon.getJSONArray("major");
System.out.print("major是:");
for (Object s : jay) {
System.out.print(s + " ");