package com.josn.demo; import java.io.FileNotFoundException; import java.io.FileReader; import com.google.gson.JsonArray; import com.google.gson.JsonIOException; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.JsonSyntaxException; /** * http://www.cnblogs.com/zhanglu-cape/p/3960029.html gson介紹 * http://www.cnblogs.com/javaee6/p/3714766.html jackjson 使用介紹 */ public class ReadJSON { public static void main(String args[]) throws FileNotFoundException{ String test = "{\"cat\":\"it\",\"language\":[{\"id\":1,\"ide\":\"eclipse\",\"name\":Java},{\"id\":2,\"ide\":\"XCode\",\"name\":\"Swift\"}, {\"id\":3,\"ide\":\"Visual Stdio\",\"name\":\"C#\"} ],\"pop\":true}"; try { /**這裏使用的是 gson的解析器 去解析 * dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.6.1</version> </dependency> */ JsonParser parser=new JsonParser(); //建立JSON解析器 //JsonObject object=(JsonObject) parser.parse(new FileReader("test.json")); //建立JsonObject對象 JsonObject object=(JsonObject) parser.parse(test); System.out.println("cat="+object.get("cat").getAsString()); //將json數據轉爲爲String型的數據 System.out.println("pop="+object.get("pop").getAsBoolean()); //將json數據轉爲爲boolean型的數據 JsonArray array=object.get("language").getAsJsonArray(); //獲得爲json的數組 for(int i=0;i<array.size();i++){ System.out.println("---------------"); JsonObject subObject=array.get(i).getAsJsonObject(); System.out.println("id="+subObject.get("id").getAsInt()); System.out.println("name="+subObject.get("name").getAsString()); System.out.println("ide="+subObject.get("ide").getAsString()); } } catch (JsonIOException e) { e.printStackTrace(); } catch (JsonSyntaxException e) { e.printStackTrace(); } } }
連接:http://blog.csdn.net/levae1024/article/details/78610566 json轉換之 -- jsonBinder