1,读取文件的公共方法。
public static String readJsonFile(String fileName) {
String jsonStr = "";
try {
File jsonFile = new File(fileName);
FileReader fileReader = new FileReader(jsonFile);
Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
int ch = 0;
StringBuffer sb = new StringBuffer();
while ((ch = reader.read()) != -1) {
sb.append((char) ch);
}
fileReader.close();
reader.close();
jsonStr = sb.toString();
return jsonStr;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
2,以城市为例,先把文件放入项目的资源文件下 我的是 : E:\\tf\\aizzb-process\\aizzb-web\\src\\main\\resources\\process\\templates\\110101.json
调用方法读取就可以了。读取的时候根据json 的结构依次解析就可以。
public static void main(String[] args) throws Exception{
String s = readJsonFile("E:\\tf\\aizzb-process\\aizzb-web\\src\\main\\resources\\process\\templates\\110101.json");
System.out.println("解析的json:"+s);
JSONObject jsonObject = JSONObject.parseObject(s);
JSONObject a = (JSONObject)jsonObject.getJSONArray("features").get(0);
System.out.println("数组第一项:"+a);
String type = a.getString("properties");
System.out.println("第一项里的对象:"+type);
JSONObject json = JSONObject.parseObject(type);
System.out.println("我们需要的城市:"+json.getString("name"));
}