JSON (JavaScript Object Notation) is a lightweight data exchange format that is widely used in front-end data transfer and API communication. It organizes data based on key-value pairs, which is convenient for human reading and machine analysis. In Java development, processing JSON data usually requires the use of some common libraries, such as Jackson, Gson, Fastjson, etc. This article will introduce the basic concepts, common operations and specific applications in Java.
1. Basic concepts of JSON
JSON's data structure includes two types:ObjectandArray。
Object:use{}
Insert, the inside is a collection of key-value pairs, and each key and value is used with a colon:
Separate, use commas between multiple key-value pairs,
Separate. For example:
{ "name": "Alice", "age": 25, "address": { "city": "New York", "zip": "10001" } }
Array:use[]
Insert, there are multiple values inside, each value separated by a comma. For example:
[ "apple", "banana", "cherry" ]
2. Common JSON processing libraries
1. Jackson
Jackson is one of the most commonly used libraries for handling JSON in Java. It can easily convert Java objects and JSON strings, and has the characteristics of being efficient, flexible and powerful.
Object to JSON:
ObjectMapper objectMapper = new ObjectMapper(); User user = new User("Alice", 25); String jsonString = (user);
JSON to object:
String jsonString = "{\"name\":\"Alice\", \"age\":25}"; User user = (jsonString, );
Jackson also supports advanced functions such as complex types of parsing, ignoring fields, and date formatting.
2. Gson
Gson is another popular JSON processing library provided by Google. It is known for its lightweight and easy to use, and is suitable for handling simple JSON data structures.
Object to JSON:
Gson gson = new Gson(); User user = new User("Bob", 30); String jsonString = (user);
JSON to object:
String jsonString = "{\"name\":\"Bob\", \"age\":30}"; User user = (jsonString, );
Gson's API style is simple and straightforward, but may be slightly inferior to Jackson in performance.
3. Fastjson
Fastjson is an open source high-performance JSON library from Alibaba, which performs well especially when parsing large amounts of JSON data.
Object to JSON:
User user = new User("Charlie", 28); String jsonString = (user);
JSON to object:
String jsonString = "{\"name\":\"Charlie\", \"age\":28}"; User user = (jsonString, );
Fastjson supports rich serialization/deserialization options and is also able to handle advanced features such as JSONPath.
3. Common operations of JSON
1. Parsing complex JSON structures
Usually the JSON we deal with is not just a simple object, but may also be a nested object or an array. Taking Jackson as an example, we can useTypeReference
to handle complex nested types.
String jsonString = "[{\"name\":\"Alice\",\"age\":25},{\"name\":\"Bob\",\"age\":30}]"; ObjectMapper mapper = new ObjectMapper(); List<User> users = (jsonString, new TypeReference<List<User>>(){});
2. JSON and Map Transfer
In actual development, sometimes we want to convert JSON data toMap<String, Object>
, to facilitate dynamic operation of data.
JSON to Map:
ObjectMapper objectMapper = new ObjectMapper(); String jsonString = "{\"name\":\"Alice\", \"age\":25}"; Map<String, Object> map = (jsonString, new TypeReference<Map<String,Object>>(){});
Map to JSON:
Map<String, Object> map = new HashMap<>(); ("name", "Alice"); ("age", 25); String jsonString = (map);
3. Process date and time formats
JSON does not support date format by default, so it needs to be handled specifically when processing date type fields. Take Jackson as an example, you can@JsonFormat
Annotation specifies the date format.
public class Event { @JsonFormat(shape = , pattern = "yyyy-MM-dd HH:mm:ss") private Date eventDate; // getters and setters }
When deserializing, it can also be configured globallyObjectMapper
In process date format:
ObjectMapper mapper = new ObjectMapper(); (new SimpleDateFormat("yyyy-MM-dd"));
4. Ignore fields
When serializing/deserializing, we may need to ignore certain unnecessary fields. Take Jackson as an example, you can@JsonIgnore
Annotation to ignore fields.
public class User { private String name; @JsonIgnore private String password; // getters and setters }
This will ensurepassword
Fields will not appear in the generated JSON.
5. Get a field in Json data
// Get the documentId in params JsonNode jsonNode = new ObjectMapper().readTree(()); if (("documentId")) { Integer documentId = ("documentId").asInt(); (documentId); if (() != null && !(())) { (record); } }
Performance comparison
Performance is an important consideration when choosing a JSON library. The following table briefly compares the performance of Jackson, Gson, and Fastjson:
characteristic | Jackson | Gson | Fastjson |
---|---|---|---|
performance | high | middle | high |
Ease of use | middle | high | middle |
Feature-rich | high | middle | high |
Community Support | powerful | powerful | powerful |
refer to:
JSON processing—FastJson, Jackson, Gson use in detail_gson fastjson-CSDN blog
This is the article about the comprehensive guide to JSON data operation and processing. For more related JSON data operation content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!