Org Json 简明教程

Org.Json - Quick Guide

org.json - Overview

org.json or JSON-Java 是一个简单的基于 Java 的 JSON 工具包。你可以使用 org.json 来编码或解码 JSON 数据。

org.json or JSON-Java is a simple Java based toolkit for JSON. You can use org.json to encode or decode JSON data.

Features

  1. Specification Compliant − JSON.simple is fully compliant with JSON Specification - RFC4627.

  2. Lightweight − It have very few classes and provides the necessary functionalities like encode/decode and escaping json.

  3. XML Conversion − It provides conversion capability from JSON to XML and vice-versa.

  4. HTTP Headers − Supports HTTP Header conversion to JSON and vice versa.

  5. Cookie − Provides support for Cookie conversion to JSON and vice versa.

  6. CDL − Provides support to convert comma separated list to JSON and vice versa.

  7. No dependency − No external library dependency. Can be independently included.

  8. Java 1.6-1.11 compatible − Source code and the binary are Java 1.6-1.11 compatible

org.json - Environment Setup

本章带你完成在基于 Windows 和 Linux 的系统上设置 Org.Json 的过程。遵循一些简单的步骤,无需任何复杂的设置过程,即可轻松安装 Org.Json 并将其与当前 Java 环境集成。安装时需要用户管理。

This chapter takes you through the process of setting up Org.Json on Windows and Linux based systems. Org.Json can be easily installed and integrated with your current Java environment following a few simple steps without any complex setup procedures. User administration is required while installation.

System Requirements

JDK

Java SE 2 JDK 1.5 or above

Memory

1 GB RAM (recommended)

Disk Space

No minimum requirement

Operating System Version

Windows XP or above, Linux

让我们继续进行安装 Org.Json 的步骤。

Let us now proceed with the steps to install Org.Json.

Step 1: Verify your Java Installation

首先,你的系统中需要安装 Java 软件开发工具包 (SDK)。要验证这一点,请根据所使用的平台执行以下两个命令。

First of all, you need to have Java Software Development Kit (SDK) installed on your system. To verify this, execute any of the two commands depending on the platform you are working on.

如果 Java 安装已正确完成,则它将显示 Java 安装的当前版本和规范。以下表中给出了一个示例输出。

If the Java installation has been done properly, then it will display the current version and specification of your Java installation. A sample output is given in the following table.

Platform

Command

Sample Output

Windows

Open command console and type − >java –version

java version "11.0.11" 2021-04-20 LTS Java™ SE Runtime Environment 18.9 (build 11.0.11+9-LTS-194) Java HotSpot™ 64-Bit Server VM 18.9 (build 11.0.11+9-LTS-194, mixed mode)

Linux

Open command terminal and type − $java –version

java version "11.0.11" 2021-04-20 LTS Open JDK Runtime Environment 18.9 (build 11.0.11+9-LTS-194) Open JDK 64-Bit Server VM (build 11.0.11+9-LTS-194, mixed mode)

  1. We assume the readers of this tutorial have Java SDK version 11.0.11 installed on their system.

  2. In case you do not have Java SDK, download its current version from www.oracle.com/technetwork/java/javase/downloads/index.html and have it installed.

Step 2: Set your Java Environment

设置环境变量 JAVA_HOME 以指向计算机上安装 Java 的基本目录位置。例如,

Set the environment variable JAVA_HOME to point to the base directory location where Java is installed on your machine. For example,

Sr.No.

Platform & Description

1

Windows Set JAVA_HOME to C:\ProgramFiles\java\jdk11.0.11

2

Linux Export JAVA_HOME = /usr/local/java-current

将 Java 编译器位置的完整路径附加到系统路径。

Append the full path of Java compiler location to the System Path.

Sr.No.

Platform & Description

1

Windows Append the String "C:\Program Files\Java\jdk11.0.11\bin" to the end of the system variable PATH.

2

Linux Export PATH = $PATH:$JAVA_HOME/bin/

如上所述,从命令提示符执行命令 java -version

Execute the command java -version from the command prompt as explained above.

Step 3: Install Org.Json Library

org.json @ MVNRepository 下载最新版本的 org.json jar 文件。在编写本教程时,我们已下载 json-20211205,并将其复制到 C:\>JSON 文件夹中。

Download the latest version of org.json jar file from org.json @ MVNRepository. At the time of writing this tutorial, we have downloaded json-20211205, and copied it into C:\>JSON folder.

OS

Archive name

Windows

json-20180813.jar

Linux

json-20180813.jar

Mac

json-20180813.jar

Step 4: Set JSON_JAVA Environment

设置 JSON_JAVA 环境变量以指向 org.json jar 存储在你机器上的基本目录位置。我们假设我们已将 json-20211205.jar 存储在 JSON 文件夹中。

Set the JSON_JAVA environment variable to point to the base directory location where org.json jar is stored on your machine. Let’s assuming we’ve stored json-20211205.jar in the JSON folder.

Sr.No

OS & Description

1

Windows Set the environment variable JSON_JAVA to C:\JSON

2

Linux export JSON_JAVA = /usr/local/JSON

3

Mac export JSON_JAVA = /Library/JSON

Step 5: Set CLASSPATH Variable

CLASSPATH 环境变量设置为指向 JSON.simple jar 所在位置。

Set the CLASSPATH environment variable to point to the JSON.simple jar location.

Sr.No

OS & Description

1

Windows Set the environment variable CLASSPATH to %CLASSPATH%;%JSON_JAVA%\json-20211205.jar;.;

2

Linux export CLASSPATH = $CLASSPATH:$JSON_JAVA/json-20211205.jar:.

3

Mac export CLASSPATH = $CLASSPATH:$JSON_JAVA/json-20211205.jar:.

org.json - CDL

CDL 类提供了将逗号分隔文本转换为 JSONArray,反之亦然,的静态方法。

CDL class provides static methods to convert a comma delimited text into a JSONArray, and vice versa.

以下方法在示例中介绍。

Following methods are covered in the example.

  1. rowToJSONArray(String) − Converts a comma delimited text to JSONArray Object.

  2. rowToString(JSONArray) − Converts a JSONArray to comma delimited text.

  3. toJSONArray(String) − Converts a multi-line comma delimited text to Object of JSONArray objects.

  4. toJSONArray(JSONArray, String) − Converts a JSONArray Object and comma delimited text to JSONArray Object.

Example

import org.json.CDL;
import org.json.JSONArray;
import org.json.JSONTokener;

public class JSONDemo {
   public static void main(String[] args) {
      String csvData = "INDIA, UK, USA";

      //Case 1: CSV to JSON Array
      JSONArray jsonArray = CDL.rowToJSONArray(new JSONTokener(csvData));
      System.out.println(jsonArray);

      //Case 2: JSONArray to CSV
      System.out.println(CDL.rowToString(jsonArray));

      //Case 3: CSV to JSONArray of Objects
      csvData = "empId, name, age \n" +
         "1, Mark, 22 \n" +
         "2, Robert, 35 \n" +
         "3, Julia, 18";
      System.out.println(CDL.toJSONArray(csvData));

      //Case 4: CSV without header
      jsonArray = new JSONArray();
      jsonArray.put("empId");
      jsonArray.put("name");
      jsonArray.put("age");
      csvData = "1, Mark, 22 \n" + "2, Robert, 35 \n" + "3, Julia, 18";
      System.out.println(CDL.toJSONArray(jsonArray,csvData));
   }
}

Output

["INDIA","UK","USA"]
INDIA,UK,USA

[{"name":"Mark","empId":"1","age":"22"},
   {"name":"Robert","empId":"2","age":"35"},
   {"name":"Julia","empId":"3","age":"18"}]
[{"name":"Mark","empId":"1","age":"22"},
   {"name":"Robert","empId":"2","age":"35"},
   {"name":"Julia","empId":"3","age":"18"}]

Cookie 类提供了将 Web 浏览器的 cookie 文本转换为 JSONObject,反之亦然,的静态方法。

Cookie class provides static methods to convert web browser’s cookie text into a JSONObject, and vice versa.

以下方法在示例中介绍。

Following methods are covered in the example.

  1. toJSONObject(String) − Converts a cookie text to JSONObject Object.

  2. toString(JSONObject) − Converts a JSONObject to cookie text.

Example

import org.json.Cookie;
import org.json.JSONObject;

public class JSONDemo {
   public static void main(String[] args) {
      String cookie = "username = Mark Den; expires = Thu, 15 Jun 2020 12:00:00 UTC; path = /";

      //Case 1: Converts Cookie String to JSONObject
      JSONObject jsonObject = Cookie.toJSONObject(cookie);
      System.out.println(jsonObject);

      //Case 2: Converts JSONObject to Cookie String
      System.out.println(Cookie.toString(jsonObject));
   }
}

Output

{"path":"/","expires":"Thu, 15 Jun 2020 12:00:00 UTC","name":"username","value":"Mark Den"}
username=Mark Den;expires=Thu, 15 Jun 2020 12:00:00 UTC;path=/

org.json - CookieList

CookieList 类提供静态方法将 Cookie 列表转换为 JSONObject,反之亦然。Cookie 列表是由名称/值对序列构成的。

CookieList class provides static methods to convert Cookie List to JSONObject, and vice versa. Cookie List is a sequence of name/value pairs.

以下方法在示例中介绍。

Following methods are covered in the example.

  1. toJSONObject(String) − Converts a cookie list text to JSONObject Object.

  2. toString(JSONObject) − Converts a JSONObject to cookie list text.

Example

import org.json.Cookie;
import org.json.CookieList;
import org.json.JSONObject;

public class JSONDemo {
   public static void main(String[] args) {
      String cookie = "username = Mark Den; expires = Thu, 15 Jun 2020 12:00:00 UTC; path = /";

      //Case 1: Converts Cookie String to JSONObject
      JSONObject cookieJSONObject = Cookie.toJSONObject(cookie);

      JSONObject cookielistJSONObject = new JSONObject();
      cookielistJSONObject.put(cookieJSONObject.getString("name"),
         cookieJSONObject.getString("value"));

      String cookieList = CookieList.toString(cookielistJSONObject);
      System.out.println(cookieList);
      System.out.println(CookieList.toJSONObject(cookieList));
   }
}

Output

username=Mark Den
{"username":"Mark Den"}

org.json - HTTP

HTTP 类提供静态方法,用于将 Web 浏览器的头部文本转换为一个 JSONObject,反之亦然。

HTTP class provides static methods to convert web browser’s header text into a JSONObject, and vice versa.

以下方法在示例中介绍。

Following methods are covered in the example.

  1. toJSONObject(String) − Converts a header text to JSONObject Object.

  2. toString(JSONObject) − Converts a JSONObject to header text.

Example

import org.json.HTTP;
import org.json.JSONObject;

public class JSONDemo {
   public static void main(String[] args) {
      JSONObject jsonObject = new JSONObject();
      jsonObject.put("Method", "POST");
      jsonObject.put("Request-URI", "http://www.tutorialspoint.com/");
      jsonObject.put("HTTP-Version", "HTTP/1.1");

      //Case 1: Converts JSONObject of Header to String
      String headerText = HTTP.toString(jsonObject);
      System.out.println(headerText);

      headerText = "POST \"http://www.tutorialspoint.com/\" HTTP/1.1";
      //Case 2: Converts Header String to JSONObject
      System.out.println(HTTP.toJSONObject(headerText));
   }
}

Output

POST "http://www.tutorialspoint.com/" HTTP/1.1

{"Request-URI":"http://www.tutorialspoint.com/","Method":"POST","HTTP-Version":"HTTP/1.1"}

org.json - JSONArray

JSONArray 是一个有序的值序列。它提供按索引访问值和放置值的方法。支持以下类型 −

A JSONArray is an ordered sequence of values. It provides methods to access values by index and to put values. Following types are supported −

  1. Boolean

  2. JSONArray

  3. JSONObject

  4. Number

  5. String

  6. JSONObject.NULL object

Example

import org.json.JSONArray;
import org.json.JSONObject;

public class JSONDemo {
   public static void main(String[] args) {
      JSONArray list = new JSONArray();

      list.put("foo");
      list.put(new Integer(100));
      list.put(new Double(1000.21));
      list.put(new Boolean(true));
      list.put(JSONObject.NULL);

      System.out.println("JSONArray: ");
      System.out.println(list);
   }
}

Output

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

org.json - JSONML

JSONML 类提供静态方法,用于将 XML 文本转换为一个 JSONArray,反之亦然。

JSONML class provides static methods to convert a XML text into a JSONArray, and vice versa.

以下方法在示例中介绍。

Following methods are covered in the example.

  1. toJSONArray(String) − Converts a XML to JSONArray Object.

  2. toJSONObject(String) − Converts a XML to JSONObject Object.

  3. toString(JSONArray) − Gives a XML from a JSONArray Object.

  4. toString(JSONObject) − Gives a XML from a JSONObject Object.

Example

import org.json.JSONArray;
import org.json.JSONML;
import org.json.JSONObject;

public class JSONDemo {
   public static void main(String[] args) {
      JSONArray list = new JSONArray();
      list.put("name");
      list.put("Robert");

      System.out.println("XML from a JSONArray: ");
      String xml = JSONML.toString(list);
      System.out.println(xml);

      System.out.println("JSONArray from a XML: ");
      list = JSONML.toJSONArray(xml);
      System.out.println(list);

      System.out.println("JSONObject from a XML: ");
      JSONObject object = JSONML.toJSONObject(xml);
      System.out.println(object);

      System.out.println("XML from a JSONObject: ");
      xml = JSONML.toString(object);
      System.out.println(xml);
   }
}

Output

XML from a JSONArray:
<name>Robert</name>
JSONArray from a XML:
["name","Robert"]
JSONObject from a XML:
{"childNodes":["Robert"],"tagName":"name"}
XML from a JSONObject:
<name>Robert</name>

org.json - JSONObject

JSONObject 类是无序的键值对集合。它提供以键访问值和放入值的方法。支持以下类型:

JSONObject class is a unordered collection of key-value pairs. It provides methods to access values by key and to put values. Following types are supported −

  1. Boolean

  2. JSONArray

  3. JSONObject

  4. Number

  5. String

  6. JSONObject.NULL object

Example

import org.json.JSONArray;
import org.json.JSONObject;

public class JSONDemo {
   public static void main(String[] args) {
      JSONObject jsonObject = new JSONObject();
      jsonObject.put("Name", "Robert");
      jsonObject.put("ID", 1);
      jsonObject.put("Fees", new Double(1000.21));
      jsonObject.put("Active", new Boolean(true));
      jsonObject.put("Other Details", JSONObject.NULL);

      JSONArray list = new JSONArray();
      list.put("foo");
      list.put(new Integer(100));
      jsonObject.put("list",list);
      System.out.println(jsonObject);
   }
}

Output

{"Active":true,"Other Details":null,"ID":1,"Fees":1000.21,"list":["foo",100],"Name":"Robert"}

org.json - JSONStringer

JSONStringer 是一个快速建立 JSON 文本的实用类,符合 JSON 语法规则。JSONStringer 的每个实例可以生成一个 JSON 文本。

JSONStringer is a utility class to build a JSON Text quickly which confirms to JSON Syntax rules. Each instance of JSONStringer can produce one JSON text.

Example

import org.json.JSONStringer;

public class JSONDemo {
   public static void main(String[] args) {
      String jsonText = new JSONStringer()
         .object()
         .key("Name")
         .value("Robert")
         .endObject()
         .toString();
      System.out.println(jsonText);

      jsonText = new JSONStringer()
         .array()
         .value("Robert")
         .value("Julia")
         .value("Dan")
         .endArray()
         .toString();
      System.out.println(jsonText);

      jsonText = new JSONStringer()
         .array()
         .value("Robert")
         .value("Julia")
         .value("Dan")
         .object()
         .key("Name")
         .value("Robert")
         .endObject()
         .endArray()
         .toString();
      System.out.println(jsonText);
   }
}

Output

{"Name":"Robert"}
["Robert","Julia","Dan"]
["Robert","Julia","Dan",{"Name":"Robert"}]

org.json - Property

Property 类提供静态方法以将属性文本转换到 JSONObject,反之亦然。

Property class provides static methods to convert properties text into a JSONObject, and vice versa.

以下方法在示例中介绍。

Following methods are covered in the example.

  1. toJSONObject(Properties) − Converts a properties data to JSONObject Object.

  2. toProperties(JSONObject) − Converts a JSONObject to properties object.

Example

import java.util.Properties;
import org.json.JSONObject;
import org.json.Property;

public class JSONDemo {
   public static void main(String[] args) {
      Properties properties = new Properties();
      properties.put("title", "This is a title text");
      properties.put("subtitle", "This is a subtitle text");

      System.out.println("Properties to JSON");
      JSONObject jsonObject = Property.toJSONObject(properties);
      System.out.println(jsonObject);

      System.out.println("JSON to properties");
      System.out.println(Property.toProperties(jsonObject));
   }
}

Output

Properties to JSON
{"subtitle":"This is a subtitle text","title":"This is a title text"}
JSON to properties
{subtitle = This is a subtitle text, title = This is a title text}

org.json - XML

XML 类提供静态方法,用于将 XML 文本转换为一个 JSONObject,反之亦然。

XML class provides static methods to convert a XML text into a JSONObject, and vice versa.

以下方法在示例中介绍。

Following methods are covered in the example.

  1. toJSONObject(String) − Converts a XML to JSONArray Object.

  2. toString(JSONObject) − Gives a XML from a JSONObject Object.

Example

import org.json.JSONObject;
import org.json.XML;

public class JSONDemo {
   public static void main(String[] args) {
      JSONObject jsonObject = new JSONObject();
      jsonObject.put("Name", "Robert");
      jsonObject.put("ID", 1);
      jsonObject.put("Fees", new Double(1000.21));
      jsonObject.put("Active", new Boolean(true));
      jsonObject.put("Details", JSONObject.NULL);

      //Convert a JSONObject to XML
      String xmlText = XML.toString(jsonObject);

      //Convert an XML to JSONObject
      System.out.println(XML.toJSONObject(xmlText));
   }
}

Output

<Active>true</Active><Details>null</Details><ID>1</ID><Fees>1000.21</Fees><Name>Robert</Name>
{"Active":true,"Details":null,"ID":1,"Fees":1000.21,"Name":"Robert"}

org.json - JSONException Handling

org.json 的实用程序类在 JSON 无效的情况下会引发 JSONException。以下示例显示如何处理 JSONException。

Utility classes of org.json throws JSONException in case of invalid JSON. Following example shows how to handle JSONException.

Example

import org.json.JSONException;
import org.json.XML;

public class JSONDemo {
   public static void main(String[] args) {
      try{
         //XML tag name should not have space.
         String xmlText = "<Other Details>null</Other Details>";
         System.out.println(xmlText);

         //Convert an XML to JSONObject
         System.out.println(XML.toJSONObject(xmlText));
      }
      catch(JSONException e){
         System.out.println(e.getMessage());
      }
   }
}

Output

<Other Details>null</Other Details>
Misshaped close tag at 34 [character 35 line 1]