zoukankan      html  css  js  c++  java
  • GsonWithoutObject 没有对象(脱离对象) 直接提取【转】

     GsonWithoutObject 没有对象(脱离对象) 直接提取 ... gson json

    GsonWithoutObject 脱离对象, 直接提取

    package temp;
    
    import tool.FileTool;
    
    import com.google.gson.JsonElement;
    import com.google.gson.JsonObject;
    import com.google.gson.JsonParser;
    
    public class GsonWithoutObjectDemo {
        
        public static void main(String[] args)  throws Exception{
            String text = FileTool.readFile("file/GsonWithoutObjectDemo.txt");
            
            JsonParser jsonParser = new JsonParser();//解析器
            JsonElement element = jsonParser.parse(text);//解析
            JsonObject jsonObj = element.getAsJsonObject();//转换成JsonObject
            
            System.out.println("jsonObj : "+jsonObj.toString());//jsonObject内容
            System.out.println("jsonObj 是否有该属性 : "+ jsonObj.has("PACKET"));//判断jsonObject 是否有PACKET属性存在
            
            String propertyValue = 
                    jsonObj.get("PACKET"). getAsJsonObject().
                                get("BODY").   getAsJsonObject().
                                get("PERSON").getAsJsonArray().get(0).getAsJsonObject().
                                get("NAME").toString();
            
            System.out.println("propertyValue="+propertyValue);
        }
    }

    file/GsonWithoutObjectDemo.txt 的gson内容

    {
      "PACKET": {
        "BODY": {
            "PERSON": [
              {
                "NAME": "bobo",
                "AGE": "18"
              },
               {
                "NAME": "sisi",
                "AGE": "33"
              }
            ]
        },
        "HEAD": {
          "TYPE": "I",
          "USERID": "50000001"
        }
      }
    }

     打印结果:

    从文件读取内容如下 : {  "PACKET": {    "BODY": {        "PERSON": [          {            "NAME": "ccc111",            "AGE": "18"          },           {            "NAME": "cccc222",            "AGE": "33"          }        ]    },    "HEAD": {      "TYPE": "I",      "USERID": "50000001"    }  }}
    jsonObj : {"PACKET":{"BODY":{"PERSON":[{"NAME":"ccc111","AGE":"18"},{"NAME":"cccc222","AGE":"33"}]},"HEAD":{"TYPE":"I","USERID":"50000001"}}}
    jsonObj 是否有该属性 : true
    propertyValue="ccc111"

    参考:

    http://www.cnblogs.com/kunpengit/p/4001680.html

  • 相关阅读:
    STM32的串口DMA收发以及双缓冲区的实现
    平衡二叉树
    二叉树的深度
    3D数学基础(四)四元数和欧拉角
    3D数学基础(三)矩阵
    3D数学基础(二)向量
    3D数学基础(一)Unity坐标系
    快速学会开发微信小程序
    苦逼的程序员
    开通博客,在这个年末,重新开始。
  • 原文地址:https://www.cnblogs.com/whatlonelytear/p/5055176.html
Copyright © 2011-2022 走看看