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.
Encoding and Decoding
Encoding
The encoding process from Java variables to JSON format is as follows:
Example
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
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
| Method | Description |
|---|---|
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 |