google-gson 解析json

http://www.cnblogs.com/jianyungsun/p/6647203.html

在JSON官网我们可以查看到各个语法对json的支持,对于java来说比较成熟的是google-gson。
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.2.4</version> </dependency> public void jsonParser(){ // 创建json解析器 JsonParser parser = new JsonParser(); // 使用解析器解析json数据,返回值是JsonElement,强制转化为其子类JsonObject类型 JsonObject object = null; try { object = (JsonObject) parser.parse(new FileReader("C:\\Users\\yf-mypc\\Desktop\\test.json")); } catch (JsonIOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JsonSyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } // 使用JsonObject的get(String memeberName)方法返回JsonElement,再使用JsonElement的getAsXXX方法得到真实类型 System.out.println("cat = " + object.get("cat").getAsString());
    // 使用JsonObject的get(String memeberName)方法返回JsonElement,再使用JsonElement的getAsXXX方法得到真实类型
    System.out.println("cat = " + object.get("cat").getAsString());

    // 遍历JSON数组
    JsonArray languages = object.getAsJsonArray("languages");
    for (JsonElement jsonElement : languages) {
        JsonObject language = jsonElement.getAsJsonObject();
        System.out.println("id = " + language.get("id").getAsInt() + ",ide = " + language.get("ide").getAsString() + ",name = " + language.get("name").getAsString());
    }

    System.out.println("pop = " + object.get("pop").getAsString());
}
现在编写程序解析以下的test.json: {
"cat":"it", "languages":[ {"id":1,"ide":"Eclipse","name":"Java"}, {"id":2,"ide":"Xcode","name":"Swift"}, {"id":3,"ide":"Visual Studio","name":"C#"} ], "pop":true }

 

     public void jsonParser(String jsonStr){
         
          JsonParser parser = new JsonParser();  // 创建json解析器
          JsonObject object = null;// 使用解析器解析json数据,返回值是JsonElement,强制转化为其子类JsonObject类型
        try {
            object = (JsonObject) parser.parse(jsonStr);
        } catch (JsonIOException e) {
            e.printStackTrace();
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
        }

          // 使用JsonObject的get(String memeberName)方法返回JsonElement,再使用JsonElement的getAsXXX方法得到真实类型
          System.out.println("systemTime = " + object.get("systemTime").getAsString());
          System.out.println("code = " + object.get("code").getAsString());
          JsonObject data = (JsonObject) object.get("data");
          System.out.println("token = " + data.get("token").getAsString() + ",userId = " + data.get("userId").getAsInt() + ",username = " + data.get("username").getAsString());

     }



jsonStr:
{"code":0,"message":"","systemTime":"2017-05-11 16:29:27","data":{"token":"6d51ba2023d34549b02b2b4733138deb_2","userId":2,"username":"empp","showname":"empp","accType":0,"orgMemberId":0}}

注意:data这里不是数组 ,所以不能按照上面那样写

 


 

posted @ 2017-05-11 16:39  Rainyn  阅读(402)  评论(0编辑  收藏  举报