GsonWithoutObject 没有对象(脱离对象) 直接提取【转】

时间:2023-03-10 02:42:56
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": ""
},
{
"NAME": "sisi",
"AGE": ""
}
]
},
"HEAD": {
"TYPE": "I",
"USERID": ""
}
}
}

打印结果:

从文件读取内容如下 : {  "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