美文网首页
java解析json数据

java解析json数据

作者: 好大一只鹏 | 来源:发表于2018-07-24 15:36 被阅读0次

    1.在进行json解析之前需要下载jar包。这里推荐使用google-gson

    public class Read {
        public static void main(String args[]){
            JsonParser parse =new JsonParser();  //创建json解析器
            try {
                JsonObject json=(JsonObject) parse.parse(new FileReader("weather.json"));  //创建jsonObject对象
                System.out.println("resultcode:"+json.get("resultcode").getAsInt());  //将json数据转为为int型的数据
                System.out.println("reason:"+json.get("reason").getAsString());     //将json数据转为为String型的数据
                 
                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进行解析,所以在使用前需要导入Gson.jar
    解析json数据时,
    1.需要进行创建Gson解析器
    2.创建JSONObject对象
    3.将json数据转为为相应的数据

    相关文章

      网友评论

          本文标题:java解析json数据

          本文链接:https://www.haomeiwen.com/subject/akxymftx.html