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
时间: 2024-12-28 00:58:32