Gson获取json串中的key-value


1、依赖包

    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.1</version>
    </dependency>

  

2、示例代码

String json = "{\"resultCode\":\"SUCCESS\",\"resultDesc\":\"SUCCESS\",\"userProfile\":{\"userId\":\"901228507\",\"registTime\":\"20180622161442\",\"accounts\":[{\"accountName\":\"123566965\",\"accoutType\":\"MOBILE\",\"bindTime\":null,\"verified\":false,\"accountExtInfo\":null}],\"avatar\":null,\"nickName\":null,\"userRole\":null,\"usernum\":null,\"extInfo\":null}}";

        JsonParser parser = new JsonParser();

        // 2.获得 根节点元素
        JsonElement element = parser.parse(json);

        // 3.根据 文档判断根节点属于 什么类型的 Gson节点对象
        JsonObject root = element.getAsJsonObject();

        String resultCode = root.get("resultCode").getAsString();

        System.out.println(resultCode);

        // 4. 取得 节点 下 的某个节点的 value
        JsonObject userProfile = root.getAsJsonObject("userProfile");

        System.out.println(userProfile.get("userId").getAsString());

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM