1. 程式人生 > >java中的JSON操作

java中的JSON操作

(1)JSON: javaScript object Notation(javaScript物件表示法)

比XML資料更小、更快、更容易解析。

資料由名稱-值 對錶示,由逗號分隔開,花括號儲存物件,方括號儲存陣列。

Json值可以是:數字/字串/邏輯值/陣列/物件/null

Json物件:物件可以包涵多個鍵值對:

{ “firstname”:”John”,“lastname“:”Doe“}

JSON陣列:可以包含多個物件

{

“employees”: [

      { “firstname”:”John”,“lastname“:”Doe“},

       {“firstname”:”aaa”,“lastname“:”bbb“ },

       {……}

]

}

(2)使用Java讀取JSON資料

www.json.org找到Java庫 à Google-gson-2.2.4下載

或直接百度搜索下載http://download.csdn.net/detail/qq_20523943/9719545

將此jar檔案放到專案中(可以新建一個Lib資料夾)

JSON資料例子:(test.json)

{

"cat":"it",

     "languages":[

     {"id":1,"name":"java","ide":"eclipse"},

     {"id":2,"name":"swift","ide":"XCode"

},

     {"id":3,"name":"C#","ide":"VIsualStudio"}

     ],

    "pop":true

}

解析程式碼:

JsonParserparser = new JsonParser();

JsonObjectobj = (JsonObject) parser.parse(new FileReader("test.json"));

System.out.println("cat=" +obj.get("cat").toString());

System.out.println("pop=" +obj.get("pop").toString());

JsonArrayarray = obj.get("languages").getAsJsonArray();

for(int i = 0;i<array.size();i++)

{

System.out.println("---------");

JsonObjectsubObjectarray.get(i).getAsJsonObject();

System.out.println("id="+subObject.get("id"));   

System.out.println("name="+subObject.get("name"));   

System.out.println("ide="+subObject.get("ide")); 

}

(3)使用Java建立JSON資料

JsonObject obj = new JsonObject();

        //addProperty是新增屬性(數值、陣列等);add是新增json物件

        obj.addProperty("cat", "it");

        obj.addProperty("pop", true);

        JsonArray array = new JsonArray();

        JsonObject lan1 = new JsonObject();

        lan1.addProperty("id", 1);

        lan1.addProperty("name","Java");

        lan1.addProperty("ide", "Eclipse");

        array.add(lan1);

        JsonObject lan2 = new JsonObject();

        lan2.addProperty("id", 2);

        lan2.addProperty("name","swift");

        lan2.addProperty("ide", "Xcode");

        array.add(lan2);

        JsonObject lan3 = new JsonObject();

        lan3.addProperty("id", 3);

        lan3.addProperty("name","C#");

        lan3.addProperty("ide", "VisualStudio");

        array.add(lan3);

        obj.add("languages", array);

        //控制檯輸出

        System.out.println(obj.toString()