1.本地json位置
2,json数据
{
"garbages":
[
{"id":"/m/011k07","ename":"Football","cname":"足球","gtype":"可回收垃圾"},
{"id":"/m/012xff","ename":"Toothbrush","cname":"牙刷","gtype":"有害垃圾"}
]
}
3依赖jar
com.alibaba
fastjson
1.2.47
4.测试代码
/**
* 读取json文件,返回json串
* @param fileName
* @return
*/
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;
}
}
/**
*解析json串
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception{
String path = GetJson.class.getClassLoader().getResource("garbage.json").getPath();
String s = readJsonFile(path);
JSONObject jobj = JSON.parseObject(s);
JSONArray garbages = jobj.getJSONArray("garbages");
for (int i = 0; i < garbages.size(); i++) {
JSONObject key1 = (JSONObject)garbages.get(i);
String id = (String)key1.get("id");
String ename = (String)key1.get("ename");
String cname = (String)key1.get("cname");
String gtype = (String)key1.get("gtype");
System.out.println(id);
System.out.println(ename);
System.out.println(cname);
System.out.println(gtype);
}
}
}