1.在進(jìn)行json解析之前需要下載jar包。這里推薦使用google-gson
public class Read {
public static void main(String args[]){
JsonParser parse =new JsonParser(); //創(chuàng)建json解析器
try {
JsonObject json=(JsonObject) parse.parse(new FileReader("weather.json")); //創(chuàng)建jsonObject對象
System.out.println("resultcode:"+json.get("resultcode").getAsInt()); //將json數(shù)據(jù)轉(zhuǎn)為為int型的數(shù)據(jù)
System.out.println("reason:"+json.get("reason").getAsString()); //將json數(shù)據(jù)轉(zhuǎn)為為String型的數(shù)據(jù)
JsonObject result=json.get("result").getAsJsonObject();
JsonObject today=result.get("today").getAsJsonObject();
System.out.println("temperature:"+today.get("temperature").getAsString());
System.out.println("weather:"+today.get("weather").getAsString());
} catch (JsonIOException e) {
e.printStackTrace();
} catch (JsonSyntaxException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
3.3-3 【分析】
我們通過Gson進(jìn)行解析前联,所以在使用前需要導(dǎo)入Gson.jar
解析json數(shù)據(jù)時,
1.需要進(jìn)行創(chuàng)建Gson解析器
2.創(chuàng)建JSONObject對象
3.將json數(shù)據(jù)轉(zhuǎn)為為相應(yīng)的數(shù)據(jù)