package bean;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.json.JSONException;
import org.json.JSONObject;
public class ReadJson {
public static void main(String[] args) throws IOException, JSONException{
File fi = new File(ReadJson.class.getResource("/wangxiaoer.json").getFile());
String content = FileUtils.readFileToString(fi);
JSONObject JO= new JSONObject(content);
System.out.println("姓名是:"+JO.getString("name"));
}
}
//ReadJSONSample.class.getResource 为项目的资源目录路径,请保证文件存在
File file=new File(ReadJSONSample.class.getResource("/wangxiaoer.json").getFile());
// 或者指定文件目录,请保证文件存存
//File file = new File("/tmp/wangxiaoer.json");
//
String content = FileUtils.readFileToString(file, StandardCharsets.UTF_8);
JSONObject jsonObject = new JSONObject(content);
System.out.println("name is " + jsonObject.getString("name"));
System.out.println("age is " + jsonObject.getDouble("age"));
把
jsonContent.json
放到resouces 路径下。在如下读取 File file = new File(ReadJsonSample.class.getClassLoader().getResource("./jsonContent.json").getPath());