JSON.simple 快速指南



JSON.simple - 概述

JSON.simple 是一個簡單的基於 Java 的 JSON 工具包。您可以使用 JSON.simple 來編碼或解碼 JSON 資料。

特性

  • 規範相容 − JSON.simple 完全符合 JSON 規範 - RFC4627。

  • 輕量級 − 它只有很少的類,並提供必要的編碼/解碼和 JSON 轉義功能。

  • 重用集合 − 大多數操作都是使用 Map/List 介面完成的,提高了可重用性。

  • 支援流 − 支援 JSON 輸出文字的流處理。

  • 類似 SAX 的內容處理器 − 提供類似 SAX 的介面來流式處理大量 JSON 資料。

  • 高效能 − 使用基於堆的解析器,提供高效能。

  • 無依賴性 − 沒有外部庫依賴性。可以獨立包含。

  • JDK1.2 相容 − 原始碼和二進位制檔案都與 JDK1.2 相容

JSON.simple - 環境設定

本地環境設定

JSON.simple 是一個 Java 庫,因此首要要求是在您的機器上安裝 JDK。

系統需求

JDK 記憶體 磁碟空間 作業系統
1.5 或更高版本。 沒有最低要求。 沒有最低要求。 沒有最低要求。

步驟 1:驗證您的機器上是否安裝了 Java

首先,開啟控制檯並執行基於您正在使用的作業系統的 java 命令。

作業系統 任務 命令
Windows 開啟命令控制檯 c:\> java -version
Linux 開啟命令終端 $ java -version
Mac 開啟終端 machine:< joseph$ java -version

讓我們驗證所有作業系統的輸出:

作業系統 輸出
Windows

java version "1.8.0_101"

Java(TM) SE Runtime Environment (build 1.8.0_101)

Linux

java version "1.8.0_101"

Java(TM) SE Runtime Environment (build 1.8.0_101)

Mac

java version "1.8.0_101"

Java(TM) SE Runtime Environment (build 1.8.0_101)

如果您的系統上沒有安裝 Java,請從以下連結下載 Java 軟體開發工具包 (SDK) www.oracle.com。在本教程中,我們假設 Java 1.8.0_101 為已安裝版本。

步驟 2:設定 JAVA 環境

設定JAVA_HOME環境變數以指向 Java 安裝在您機器上的基目錄位置。例如:

作業系統 輸出
Windows 將環境變數 JAVA_HOME 設定為 C:\Program Files\Java\jdk1.8.0_101
Linux export JAVA_HOME = /usr/local/java-current
Mac export JAVA_HOME = /Library/Java/Home

將 Java 編譯器位置新增到系統路徑。

作業系統 輸出
Windows 在系統變數Path的末尾追加字串C:\Program Files\Java\jdk1.8.0_101\bin
Linux export PATH = $PATH:$JAVA_HOME/bin/
Mac 無需設定

使用上面解釋的命令java -version驗證 Java 安裝。

步驟 3:下載 JSON.simple 存檔

json-simple @ MVNRepository下載最新版本的 JSON.simple jar 檔案。在撰寫本教程時,我們下載了 json-simple-1.1.1.jar,並將其複製到 C:\>JSON 資料夾中。

作業系統 存檔名稱
Windows json-simple-1.1.1.jar
Linux json-simple-1.1.1.jar
Mac json-simple-1.1.1.jar

步驟 4:設定 JSON_JAVA 環境

設定JSON_JAVA環境變數以指向 JSON.simple jar 儲存在您機器上的基目錄位置。假設我們將 json-simple-1.1.1.jar 儲存在 JSON 資料夾中。

序號 作業系統和說明
1

Windows

將環境變數 JSON_JAVA 設定為 C:\JSON

2

Linux

export JSON_JAVA = /usr/local/JSON

3

Mac

export JSON_JAVA = /Library/JSON

步驟 5:設定 CLASSPATH 變數

設定CLASSPATH環境變數以指向 JSON.simple jar 位置。

序號 作業系統和說明
1

Windows

將環境變數 CLASSPATH 設定為 %CLASSPATH%;%JSON_JAVA%\json-simple-1.1.1.jar;.;

2

Linux

export CLASSPATH = $CLASSPATH:$JSON_JAVA/json-simple-1.1.1.jar:.

3

Mac

export CLASSPATH = $CLASSPATH:$JSON_JAVA/json-simple-1.1.1.jar:.

JSON.simple - JAVA對映

在解碼或解析時,JSON.simple 將左側的實體對映到右側,而在編碼時將右側的實體對映到左側。

JSON Java
字串 java.lang.String
數字 java.lang.Number
true|false java.lang.Boolean
null null
陣列 java.util.List
物件 java.util.Map

解碼時,java.util.List 的預設具體類是 org.json.simple.JSONArrayjava.util.Map 的預設具體類是 org.json.simple.JSONObject

JSON.simple - 轉義特殊字元

以下字元是保留字元,不能在 JSON 中使用,必須正確轉義才能在字串中使用。

  • 退格鍵 將被替換為 \b

  • 換頁符 將被替換為 \f

  • 換行符 將被替換為 \n

  • 回車符 將被替換為 \r

  • 製表符 將被替換為 \t

  • 雙引號 將被替換為 \"

  • 反斜槓 將被替換為 \\

JSONObject.escape() 方法可以用來轉義 JSON 字串中的這些保留關鍵字。以下是一個示例:

示例

import org.json.simple.JSONObject;

public class JsonDemo {
   public static void main(String[] args) {
      JSONObject jsonObject = new JSONObject();
      String text = "Text with special character /\"\'\b\f\t\r\n.";
      System.out.println(text);
      System.out.println("After escaping.");
      text = jsonObject.escape(text);
      System.out.println(text);
   }
}

輸出

Text with special character /"'
.
After escaping.
Text with special character \/\"'\b\f\t\r\n.

JSON.simple - 使用JSONValue

JSONValue 提供了一個靜態方法 parse() 來解析給定的 json 字串,返回一個 JSONObject,然後可以使用它來獲取解析的值。請參見下面的示例:

示例

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

public class JsonDemo {
   public static void main(String[] args) {
      String s = "[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";
      Object obj = JSONValue.parse(s);
      JSONArray array = (JSONArray)obj;

      System.out.println("The 2nd element of array");
      System.out.println(array.get(1));
      System.out.println();

      JSONObject obj2 = (JSONObject)array.get(1);
      System.out.println("Field \"1\"");
      System.out.println(obj2.get("1"));    

      s = "{}";
      obj = JSONValue.parse(s);
      System.out.println(obj);

      s = "[5,]";
      obj = JSONValue.parse(s);
      System.out.println(obj);

      s = "[5,,2]";
      obj = JSONValue.parse(s);
      System.out.println(obj);
   }
}

輸出

The 2nd element of array
{"1":{"2":{"3":{"4":[5,{"6":7}]}}}}

Field "1"
{"2":{"3":{"4":[5,{"6":7}]}}}
{}
[5]
[5,2]

JSON.simple - 異常處理

JSONParser.parse() 在 JSON 無效的情況下會丟擲 ParseException。下面的示例顯示瞭如何處理 ParseException。

示例

import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

class JsonDemo {
   public static void main(String[] args) {
      JSONParser parser = new JSONParser();
      String text = "[[null, 123.45, \"a\tb c\"]}, true";

      try{
         Object obj = parser.parse(text);         
         System.out.println(obj);
      }catch(ParseException pe) {
         System.out.println("position: " + pe.getPosition());
         System.out.println(pe);
      }
   }
}

輸出

position: 24
Unexpected token RIGHT BRACE(}) at position 24.

JSON.simple - 容器工廠

ContainerFactory 可用於為解析的 JSON 物件/陣列建立自定義容器。首先,我們需要建立一個 ContainerFactory 物件,然後在 JSONParser 的 parse 方法中使用它來獲取所需的物件。請參見下面的示例:

示例

import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.json.simple.parser.ContainerFactory;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

class JsonDemo {
   public static void main(String[] args) {
      JSONParser parser = new JSONParser();
      String text =  "{\"first\": 123, \"second\": [4, 5, 6], \"third\": 789}";
      ContainerFactory containerFactory = new ContainerFactory() {
         @Override
         public Map createObjectContainer() {
            return new LinkedHashMap<>();
         }
         @Override
         public List creatArrayContainer() {
            return new LinkedList<>();
         }
      };
      try {
         Map map = (Map)parser.parse(text, containerFactory);       
         map.forEach((k,v)->System.out.println("Key : " + k + " Value : " + v));
      } catch(ParseException pe) {
         System.out.println("position: " + pe.getPosition());
         System.out.println(pe);
      }
   }
}

輸出

Key : first Value : 123
Key : second Value : [4, 5, 6]
Key : third Value : 789

JSON.simple - 內容處理器

ContentHandler 介面用於提供類似 SAX 的介面來流式處理大型 json。它也提供可停止功能。下面的示例說明了這個概念。

示例

import java.io.IOException;
import java.util.List;
import java.util.Stack;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.ContentHandler;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

class JsonDemo {
   public static void main(String[] args) {
      JSONParser parser = new JSONParser();
      String text =  "{\"first\": 123, \"second\": [4, 5, 6], \"third\": 789}";
      try {
         CustomContentHandler handler = new CustomContentHandler();
         parser.parse(text, handler,true);       
      } catch(ParseException pe) {
      }
   }
}
class CustomContentHandler implements ContentHandler {
   @Override
   public boolean endArray() throws ParseException, IOException {     
      System.out.println("inside endArray");
      return true;
   }
   @Override
   public void endJSON() throws ParseException, IOException {
      System.out.println("inside endJSON");
   }
   @Override
   public boolean endObject() throws ParseException, IOException {       
      System.out.println("inside endObject");
      return true;
   }
   @Override
   public boolean endObjectEntry() throws ParseException, IOException {
      System.out.println("inside endObjectEntry");
      return true;
   }
   public boolean primitive(Object value) throws ParseException, IOException {
      System.out.println("inside primitive: " + value);
      return true;
   }
   @Override
   public boolean startArray() throws ParseException, IOException {
      System.out.println("inside startArray");
      return true;
   }
   @Override
   public void startJSON() throws ParseException, IOException {
      System.out.println("inside startJSON");
   }
   @Override
   public boolean startObject() throws ParseException, IOException {
      System.out.println("inside startObject");      
      return true;
   }
   @Override
   public boolean startObjectEntry(String key) throws ParseException, IOException {
      System.out.println("inside startObjectEntry: " + key); 
      return true;
   }    
}

輸出

inside startJSON
inside startObject
inside startObjectEntry: first
inside primitive: 123
inside endObjectEntry
inside startObjectEntry: second
inside startArray
inside primitive: 4
inside primitive: 5
inside primitive: 6
inside endArray
inside endObjectEntry
inside startObjectEntry: third
inside primitive: 789
inside endObjectEntry
inside endObject
inside endJSON

JSON.simple - 編碼JSONObject

使用 JSON.simple,我們可以透過以下方式編碼 JSON 物件:

  • 編碼 JSON 物件 - 到字串 - 簡單編碼。

  • 編碼 JSON 物件 - 流 - 輸出可用於流處理。

  • 編碼 JSON 物件 - 使用 Map - 保持順序的編碼。

  • 編碼 JSON 物件 - 使用 Map 和流 - 保持順序並進行流處理的編碼。

下面的示例說明了上述概念。

示例

import java.io.IOException;
import java.io.StringWriter;
import java.util.LinkedHashMap;
import java.util.Map;

import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

class JsonDemo {
   public static void main(String[] args) throws IOException {
      JSONObject obj = new JSONObject();
      String jsonText;

      obj.put("name", "foo");
      obj.put("num", new Integer(100));
      obj.put("balance", new Double(1000.21));
      obj.put("is_vip", new Boolean(true));
      jsonText = obj.toString();

      System.out.println("Encode a JSON Object - to String");
      System.out.print(jsonText);

      StringWriter out = new StringWriter();
      obj.writeJSONString(out);       
      jsonText = out.toString();

      System.out.println("\nEncode a JSON Object - Streaming");       
      System.out.print(jsonText);

      Map obj1 = new LinkedHashMap();
      obj1.put("name", "foo");
      obj1.put("num", new Integer(100));
      obj1.put("balance", new Double(1000.21));
      obj1.put("is_vip", new Boolean(true));

      jsonText = JSONValue.toJSONString(obj1); 
      System.out.println("\nEncode a JSON Object - Preserving Order");
      System.out.print(jsonText);

      out = new StringWriter();
      JSONValue.writeJSONString(obj1, out); 
      jsonText = out.toString();
      System.out.println("\nEncode a JSON Object - Preserving Order and Stream");
      System.out.print(jsonText);
   }
}

輸出

Encode a JSON Object - to String
{"balance":1000.21,"is_vip":true,"num":100,"name":"foo"}
Encode a JSON Object - Streaming
{"balance":1000.21,"is_vip":true,"num":100,"name":"foo"}
Encode a JSON Object - Preserving Order
{"name":"foo","num":100,"balance":1000.21,"is_vip":true}
Encode a JSON Object - Preserving Order and Stream
{"name":"foo","num":100,"balance":1000.21,"is_vip":true}

JSON.simple - 編碼JSONArray

使用 JSON.simple,我們可以透過以下方式編碼 JSON 陣列:

  • 編碼 JSON 陣列 - 到字串 - 簡單編碼。

  • 編碼 JSON 陣列 - 流 - 輸出可用於流處理。

  • 編碼 JSON 陣列 - 使用 List - 使用 List 進行編碼。

  • 編碼 JSON 陣列 - 使用 List 和流 - 使用 List 並進行流處理的編碼。

下面的示例說明了上述概念。

示例

import java.io.IOException;
import java.io.StringWriter;
import java.util.LinkedList;
import java.util.List;

import org.json.simple.JSONArray;
import org.json.simple.JSONValue;

class JsonDemo {
   public static void main(String[] args) throws IOException {
      JSONArray list = new JSONArray();
      String jsonText;

      list.add("foo");
      list.add(new Integer(100));
      list.add(new Double(1000.21));
      list.add(new Boolean(true));
      list.add(null);
      jsonText = list.toString();

      System.out.println("Encode a JSON Array - to String");
      System.out.print(jsonText);

      StringWriter out = new StringWriter();
      list.writeJSONString(out);       
      jsonText = out.toString();

      System.out.println("\nEncode a JSON Array - Streaming");       
      System.out.print(jsonText);

      List list1 = new LinkedList();
      list1.add("foo");
      list1.add(new Integer(100));
      list1.add(new Double(1000.21));
      list1.add(new Boolean(true));
      list1.add(null);

      jsonText = JSONValue.toJSONString(list1); 
      System.out.println("\nEncode a JSON Array - Using List");
      System.out.print(jsonText);

      out = new StringWriter();
      JSONValue.writeJSONString(list1, out); 
      jsonText = out.toString();
      System.out.println("\nEncode a JSON Array - Using List and Stream");
      System.out.print(jsonText);
   }
}

輸出

Encode a JSON Array - to String
["foo",100,1000.21,true,null]
Encode a JSON Array - Streaming
["foo",100,1000.21,true,null]
Encode a JSON Array - Using List
["foo",100,1000.21,true,null]
Encode a JSON Array - Using List and Stream
["foo",100,1000.21,true,null]

JSON.simple - 合併物件

在 JSON.simple 中,我們可以使用 JSONObject.putAll() 方法輕鬆合併兩個 JSON 物件。

下面的示例說明了上述概念。

示例

import java.io.IOException;
import org.json.simple.JSONObject;

class JsonDemo {
   public static void main(String[] args) throws IOException {
      JSONObject obj1 = new JSONObject();       
      obj1.put("name", "foo");
      obj1.put("num", new Integer(100)); 

      JSONObject obj2 = new JSONObject();       
      obj2.put("balance", new Double(1000.21));
      obj2.put("is_vip", new Boolean(true));       
      obj1.putAll(obj2);       
      System.out.println(obj1);
   }
}

輸出

{"balance":1000.21,"is_vip":true,"num":100,"name":"foo"}

JSON.simple - 合併陣列

在 JSON.simple 中,我們可以使用 JSONArray.addAll() 方法輕鬆合併兩個 JSON 陣列。

下面的示例說明了上述概念。

示例

import java.io.IOException;
import org.json.simple.JSONArray;

class JsonDemo {
   public static void main(String[] args) throws IOException {
      JSONArray list1 = new JSONArray();
      list1.add("foo");
      list1.add(new Integer(100));

      JSONArray list2 = new JSONArray();       
      list2.add(new Double(1000.21));
      list2.add(new Boolean(true));
      list2.add(null);

      list1.addAll(list2);       
      System.out.println(list1);       
   }
}

輸出

["foo",100,1000.21,true,null]

JSON.simple - 原生型別、物件、陣列

使用 JSONArray 物件,我們可以建立一個包含原生型別、物件和陣列的 JSON。

下面的示例說明了上述概念。

示例

import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

class JsonDemo {
   public static void main(String[] args) throws IOException {
      JSONArray list1 = new JSONArray();
      list1.add("foo");
      list1.add(new Integer(100));

      JSONArray list2 = new JSONArray();       
      list2.add(new Double(1000.21));
      list2.add(new Boolean(true));
      list2.add(null);

      JSONObject obj = new JSONObject();

      obj.put("name", "foo");
      obj.put("num", new Integer(100));
      obj.put("balance", new Double(1000.21));
      obj.put("is_vip", new Boolean(true));
     
      obj.put("list1", list1); 
      obj.put("list2", list2);
      System.out.println(obj);       
   }
}

輸出

{"list1":["foo",100],"balance":1000.21,"is_vip":true,"num":100,"list2":[1000.21,true,null],"name":"foo"}

JSON.simple - 原生型別、Map、List 組合

使用 JSONValue 物件,我們可以建立一個包含原生型別、Map 和 List 的 JSON。

下面的示例說明了上述概念。

示例

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.json.simple.JSONValue;

class JsonDemo {
   public static void main(String[] args) throws IOException {
      Map m1 = new LinkedHashMap(); 
      m1.put("k11","v11"); 
      m1.put("k12","v12"); 
      m1.put("k13", "v13");

      List l1 = new LinkedList();
      l1.add(m1);
      l1.add(new Integer(100));

      String jsonString = JSONValue.toJSONString(l1);
      System.out.println(jsonString);
   }
}

輸出

[{"k11":"v11","k12":"v12","k13":"v13"},100]

JSON.simple - 原生型別、物件、Map、List

使用 JSONValue 物件,我們可以建立一個包含原生型別、物件、Map 和 List 的 JSON。

下面的示例說明了上述概念。

示例

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

class JsonDemo {
   public static void main(String[] args) throws IOException {
      JSONObject obj = new JSONObject();

      Map m1 = new LinkedHashMap(); 
      m1.put("k11","v11");
      m1.put("k12","v12");
      m1.put("k13", "v13");

      List l1 = new LinkedList();      
      l1.add(new Integer(100));

      obj.put("m1", m1);
      obj.put("l1", l1);
      String jsonString = JSONValue.toJSONString(obj);
      System.out.println(jsonString);
   }
}

輸出

{"m1":{"k11":"v11","k12":"v12","k13":"v13"},"l1":[100]}

JSON.simple - 自定義輸出

我們可以根據自定義類自定義 JSON 輸出。唯一的要求是實現 JSONAware 介面。

下面的示例說明了上述概念。

示例

import java.io.IOException;

import org.json.simple.JSONArray;
import org.json.simple.JSONAware;
import org.json.simple.JSONObject;

class JsonDemo {
   public static void main(String[] args) throws IOException {
      JSONArray students = new JSONArray(); 
      students.add(new Student(1,"Robert")); 
      students.add(new Student(2,"Julia")); 

      System.out.println(students);     
   }
}
class Student implements JSONAware {
   int rollNo;
   String name;
   Student(int rollNo, String name){
      this.rollNo = rollNo;
      this.name = name;
   }
   @Override
   public String toJSONString() {
      StringBuilder sb = new StringBuilder();
      sb.append("{");
      sb.append("name");
      sb.append(":");
      sb.append("\"" + JSONObject.escape(name) + "\"");
      sb.append(",");
      sb.append("rollNo");
      sb.append(":");
      sb.append(rollNo);
      sb.append("}");
      return sb.toString();
   }    
}

輸出

[{name:"Robert",rollNo:1},{name:"Julia",rollNo:2}]

JSON.simple - 自定義輸出流

我們可以根據自定義類自定義 JSON 流輸出。唯一的要求是實現 JSONStreamAware 介面。

下面的示例說明了上述概念。

示例

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.LinkedHashMap;
import java.util.Map;

import org.json.simple.JSONArray;
import org.json.simple.JSONStreamAware;
import org.json.simple.JSONValue;

class JsonDemo {
   public static void main(String[] args) throws IOException {
      JSONArray students = new JSONArray(); 
      students.add(new Student(1,"Robert")); 
      students.add(new Student(2,"Julia")); 
      StringWriter out = new StringWriter();
      students.writeJSONString(out); 
      System.out.println(out.toString());     
   }
}
class Student implements JSONStreamAware {
   int rollNo;
   String name;

   Student(int rollNo, String name){
      this.rollNo = rollNo;
      this.name = name;
   }
   @Override
   public void writeJSONString(Writer out) throws IOException {
      Map obj = new LinkedHashMap();
      obj.put("name", name);
      obj.put("rollNo", new Integer(rollNo));
      JSONValue.writeJSONString(obj, out);        
   }    
}

輸出

[{name:"Robert",rollNo:1},{name:"Julia",rollNo:2}]
廣告