淺談使用java解析和產生JSON_java

來源:互聯網
上載者:User

JSON概述

JSON即javascript object notation,是javascript對象標記法的子集。具有以下特點:

資料放在索引值對中;
資料由逗號分隔;
花括弧表示對象;
方括弧表示數組。

JSON的值可以是:

數字(整數或浮點數)
字串(在雙引號中)
邏輯值(true或false)
數組(方括弧內)
對象(花括弧內)
null

JSON的基本文法

JSON對象

JSON對象在花括弧中書寫,對象可以包含多個索引值對,例如:

{  "firstName":"John",  "lastName":"Doe"}

JSON數組

JSON數組在方括弧中書寫,數組中可以包含多個對象,例如:

{  "employees":[    {"firstName":"John","lastName":"Doe"},    {"firstName":"Anna","lastName":"Smith"},    {"firstName":"Peter","lastName":"Jones"}  ]}

在以上的執行個體中,根部的花括弧表示這是一個JSON對象,該對象的鍵是employees,值是一個JSON數組,在這個數組中有3個JSON對象,每個JSON對象之間也使用逗號分隔。

使用java讀取JSON資料

在JSON官網我們可以查看到各個文法對json的支援,對於java來說比較成熟的是google-gson。

其maven依賴如下:

<dependency>  <groupId>com.google.code.gson</groupId>  <artifactId>gson</artifactId>  <version>2.2.4</version></dependency>

現在編寫程式解析以下的test.json:

{  "cat":"it",  "languages":[    {"id":1,"ide":"Eclipse","name":"Java"},    {"id":2,"ide":"Xcode","name":"Swift"},    {"id":3,"ide":"Visual Studio","name":"C#"}  ],  "pop":true}

以下的代碼將解析以上的json資料:

public void readJSON() throws Exception{  // 建立json解析器  JsonParser parser = new JsonParser();   // 使用解析器解析json資料,傳回值是JsonElement,強制轉化為其子類JsonObject類型  JsonObject object = (JsonObject) parser.parse(new FileReader("test.json"));  // 使用JsonObject的get(String memeberName)方法返回JsonElement,再使用JsonElement的getAsXXX方法得到真實類型  System.out.println("cat = " + object.get("cat").getAsString());  // 遍曆JSON數組  JsonArray languages = object.getAsJsonArray("languages");  for (JsonElement jsonElement : languages) {    JsonObject language = jsonElement.getAsJsonObject();    System.out.println("id = " + language.get("id").getAsInt() + ",ide = " + language.get("ide").getAsString() + ",name = " + language.get("name").getAsString());  }  System.out.println("pop = " + object.get("pop").getAsString());}

使用java產生JSON資料

產生JSON資料的關鍵是JSON對象中的add和addProperty兩個方法。前者用於向JSON對象中添加數組或者另一個JSON對象,後者用於為JSON對象添加屬性。以下的代碼將產生上面例子中的test.json。

public void createJSON() throws IOException{  JsonObject object = new JsonObject(); // 建立一個json對象  object.addProperty("cat", "it");    // 為json對象添加屬性    JsonArray languages = new JsonArray(); // 建立json數組  JsonObject language = new JsonObject();  language.addProperty("id", 1);  language.addProperty("ide", "Eclipse");  language.addProperty("name", "java");  languages.add(language);        // 將json對象添加到數組   language = new JsonObject();  language.addProperty("id", 2);  language.addProperty("ide", "XCode");  language.addProperty("name", "Swift");  languages.add(language);  language = new JsonObject();  language.addProperty("id", 3);  language.addProperty("ide", "Visual Studio");  language.addProperty("name", "C#");  languages.add(language);  object.add("languages", languages);  // 將數組添加到json對象    object.addProperty("pop", true);  String jsonStr = object.toString();  // 將json對象轉化成json字串  PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("data.json")));  pw.print(jsonStr);  pw.flush();  pw.close();}

在JAVA中構造和解析JSON我用的是org.json,下面是兩個函數,一個是建立JSON,一個是從文本構造JSON並解析之。

建立json

//construct json and output it  public String jsonTest() throws JSONException{   JSONObject json=new JSONObject();   JSONArray jsonMembers = new JSONArray();   JSONObject member1 = new JSONObject();   member1.put("loginname", "zhangfan");   member1.put("password", "userpass");   member1.put("email","10371443@qq.com");   member1.put("sign_date", "2007-06-12");   jsonMembers.put(member1);    JSONObject member2 = new JSONObject();   member2.put("loginname", "zf");   member2.put("password", "userpass");   member2.put("email","8223939@qq.com");   member2.put("sign_date", "2008-07-16");   jsonMembers.put(member2);   json.put("users", jsonMembers);    return json.toString(); } 

 解析json

//construct json from String and resolve it. public String jsonTest2() throws JSONException{   String jsonString="{\"users\":[{\"loginname\":\"zhangfan\",\"password\":\"userpass\",\"email\":\"10371443@qq.com\"},{\"loginname\":\"zf\",\"password\":\"userpass\",\"email\":\"822393@qq.com\"}]}";   JSONObject json= new JSONObject(jsonString);   JSONArray jsonArray=json.getJSONArray("users");   String loginNames="loginname list:";   for(int i=0;i<jsonArray.length();i++){     JSONObject user=(JSONObject) jsonArray.get(i);     String userName=(String) user.get("loginname");     if(i==jsonArray.length()-1){       loginNames+=userName;     }else{       loginNames+=userName+",";     }   }   return loginNames; } 

 JAVA中處理JSON還是相當方便的。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.