java解析json數(shù)據(jù)

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ù)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容