In this chapter, we will introduce how to use JSON in the Java language.

Library Selection

Java does not have built-in JSON parsing, so using JSON requires a third-party library.

The following are several commonly used JSON parsing libraries:

  • Gson: A JSON library developed by Google, with very comprehensive functionality.
  • FastJson: A JSON library developed by Alibaba, with excellent performance.
  • Jackson: The community is very active and updates are very fast.

The following tutorial is based on FastJson.

Environment Setup

In a Maven-built project, just add the following dependency to the pom.xml file.

<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.47</version> </dependency>

Encoding and Decoding

Encoding

The encoding process from Java variables to JSON format is as follows:

Example

public void testJson() { JSONObject object = new JSONObject(); //string object.put("string","string"); //int object.put("int",2); //boolean object.put("boolean",true); //array List<Integer> integers = Arrays.asList(1,2,3); object.put("list",integers); //null object.put("null",null); ​ System.out.println(object); }

In the above example, first create a JSON object, then add a string, an integer, a boolean, and an array in order, and finally print it as a string.

The output result is as follows:

{"boolean":true,"string":"string","list":[1,2,3],"int":2}

Decoding

The decoding process from JSON objects to Java variables is as follows:

Example

public void testJson2() { ​ JSONObject object = JSONObject .parseObject("{\"boolean\":true,\"string\":\"string\",\"list\":[1,2,3],\"int\":2}"); //string String s = object.getString("string"); System.out.println(s); //int int i = object.getIntValue("int"); System.out.println(i); //boolean boolean b = object.getBooleanValue("boolean"); System.out.println(b); //list List<Integer> integers = JSON.parseArray(object.getJSONArray("list").toJSONString(),Integer.class); integers.forEach(System.out::println); //null System.out.println(object.getString("null")); ​ }

In the above example, first construct a JSON object from a string in JSON format, then read the string, integer, boolean, and array in order, and finally print them separately. The printed result is as follows:

string
2
true
1
2
3
null

Conversion between JSON Objects and Strings

MethodDescription
JSON.parseObject()Parse a JSON object from a string
JSON.parseArray()Parse a JSON array from a string
JSON.toJSONString(obj/array)Convert a JSON object or JSON array to a string

Example

//Parse a JSON object from a string JSONObject obj = JSON.parseObject("{\"example\":\"Example\"}"); //Parse a JSON array from a string JSONArray arr = JSON.parseArray("[\"Example\",\"EXAMPLE\"]\n"); //Convert a JSON object to a string String objStr = JSON.toJSONString(obj); //Convert a JSON array to a string String arrStr = JSON.toJSONString(arr);

Related Tutorials