19.JAVA-從文件中解析json、並寫入Json文件(詳解)

  • 2019 年 12 月 19 日
  • 筆記

1.json介紹

json與xml相比, 對數據的描述性比XML較差,但是數據體積小,傳遞速度更快.

json數據的書寫格式是"名稱:值對",比如:

"Name" : "John"                        //name為名稱,值對為"john"字元串

值對類型共分為:

  • 數字(整數或浮點數)
  • 字元串(在雙引號中)
  • 邏輯值(true 或 false)
  • 數組(在方括弧[]中)
  • 對象(在花括弧{}中)
  • null

當然數組也可以包含多對象:

{      "employees": [          { "Name":"John" , "Age":19 },          { "Name":"Anna" , "Age":22 },          { "Name":"Peter", "Age":23 }      ]  }

表示"employees"對象中有3個對象數組(每個對象數組表示一條員工資訊),其中並列的數據都必須用逗號","隔開.

2.json包使用

在www.json.org上公布了很多JAVA下的json解析工具(還有C/C++等等相關的),其中org.json和json-lib比較簡單,兩者使用上差不多,這裡我們使用org.json,org.json下載地址為: https://search.maven.org/search?q=g:org.json%20AND%20a:json&core=gav

3.json解析

3.1解析步驟

  • 首先通過new JSONObject(String)來構造一個json對象,並將json字元串傳遞進來.
  • 然後通過getXXX(String key)方法去獲取對應的值.

3.2 example.json示例文件如下:

{      "FLAG": 1,      "NAME": "example",      "ARRAYS":      [          {              "Name":       "array1",              "String":     "哈哈噠1"          },          {              "Name":       "array2",              "String":     "哈哈噠2"          },          {              "Name":       "array3",              "String":     "哈哈噠3"          },          {              "Name":       "array4",              "String":     "哈哈噠4"          }      ]  }

3.3解析程式碼如下:

@Test        public void JsonParser() throws Exception{            char cbuf[] = new char[10000];          InputStreamReader input =new InputStreamReader(new FileInputStream(new File("src//example.json")),"UTF-8");          int len =input.read(cbuf);          String text =new String(cbuf,0,len);          //1.構造一個json對象          JSONObject obj = new JSONObject(text.substring(text.indexOf("{")));   //過濾讀出的utf-8前三個標籤位元組,從{開始讀取            //2.通過getXXX(String key)方法獲取對應的值          System.out.println("FLAG:"+obj.getString("FLAG"));          System.out.println("NAME:"+obj.getString("NAME"));            //獲取數組          JSONArray arr = obj.getJSONArray("ARRAYS");          System.out.println("數組長度:"+arr.length());          for(int i=0;i<arr.length();i++)          {              JSONObject subObj = arr.getJSONObject(i);              System.out.println("數組Name:"+subObj.getString("Name")+" String:"+subObj.getString("String"));          }        }

列印如下:

4.寫json文件

4.1寫json步驟

  • 首先通過new JSONObject()來構造一個空的json對象
  • 如果要寫單對象內容,則通過JSONObject .put(key,value)來寫入
  • 如果要寫多數組對象內容,則通過JSONObject .accumulate (key,value)來寫入
  • 最後通過JSONObject .toString()把數據導入到文件中.

4.2寫示例如下:

@Test      public void JsonWrite() throws Exception{            OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("exampleWrite.json"),"UTF-8");            JSONObject obj=new JSONObject();//創建JSONObject對象            obj.put("FLAG","1");for(Integer i=1;i<4;i++)          {              JSONObject subObj=new JSONObject();//創建對象數組裡的子對象              subObj.put("Name","array"+i);              subObj.put("String","小白"+i);              obj.accumulate("ARRAYS",subObj);          }          System.out.println(obj.toString());            osw.write(obj.toString());          osw.flush();//清空緩衝區,強制輸出數據          osw.close();//關閉輸出流  }

列印如下: