Preface
In Java development, parsing JSON is a very common requirement.
Whether it is interacting with the front-end, calling third-party interfaces, or processing configuration files, JSON is almost impossible to avoid.
This article summarizes 6 mainstream JSON parsing methods, I hope it will be helpful to you.
1. Use Jackson: Industry standard
Functional Features
- Powerful serialization and deserialization: Supports converting JSON strings into Java objects, and also supports converting Java objects into JSON.
- Supports complex structures: It is very easy to handle nested objects, arrays, generics and other scenarios.
-
Support annotations:like
@JsonIgnore
、@JsonProperty
etc., able to finely control the behavior of serialization and deserialization. - High performance: Jackson's performance is excellent and is the first choice for many enterprise-level projects.
Code Example
1. JSON to object (deserialization)
import ; public class JacksonExample { public static void main(String[] args) throws Exception { String json = "{"id":1,"name":"Zhang San"}"; ObjectMapper objectMapper = new ObjectMapper(); User user = (json, ); (()); // Output: Zhang San } } class User { private int id; private String name; // Getters and Setters are omitted}
2. Object to JSON (serialization)
User user = new User(); (1); ("Li Si"); ObjectMapper objectMapper = new ObjectMapper(); String json = (user); (json); // Output: {"id":1,"name":"Li Si"}
Advanced features
-
Date formatting:
@JsonFormat(pattern = "yyyy-MM-dd")
-
Ignore fields:
@JsonIgnore
-
Rename the field:
@JsonProperty("custom_name")
Pros and cons
advantage | shortcoming |
---|---|
Comprehensive functions and support complex scenarios | More configurations, slightly higher learning costs |
High performance, active community, first choice for enterprise-level projects | Too powerful, some functions are not available |
Rich annotation support to facilitate control of serialization behavior | The library is large in size and is a bit bulky for small projects |
2. Use Gson: Lightweight and easy to use
Functional Features
- Lightweight:Gson's design is very simple and has a small amount of code, making it suitable for small and medium-sized projects.
- Supports generics: Can easily parse JSON with generics.
-
Annotation control: Supports controlling serialization behavior through annotations, such as
@Expose
。 - Easy to expand: You can handle complex scenarios through custom serializers and deserializers.
Code Example
1. JSON to object
import ; public class GsonExample { public static void main(String[] args) { String json = "{"id":1,"name":"Wang Wu"}"; Gson gson = new Gson(); User user = (json, ); (()); // Output: Wang Wu } }
2. Object to JSON
User user = new User(); (2); ("Zhao Liu"); Gson gson = new Gson(); String json = (user); (json); // Output: {"id":2,"name":"Zhao Liu"}
Advanced features
Ignore fields:@Expose
@Expose private String name;
Custom serializer/deserializer:
Gson gson = new GsonBuilder() .registerTypeAdapter(, new CustomSerializer()) .create();
Pros and cons
advantage | shortcoming |
---|---|
Lightweight, simple and easy to use, suitable for small and medium-sized projects | Performance is slightly inferior to Jackson |
The learning curve is smooth, making it easy for novices to get started | Not as rich as Jackson |
Provide good expansion capabilities | It's more troublesome to process complex objects |
3. Using FastJSON: High Performance
Functional Features
- Excellent performance: FastJSON's parsing speed is very fast and is suitable for large data scenarios.
- Support dynamic fields: Can easily handle dynamic JSON data.
- Powerful type support: Supports complex structures such as nested objects, generics, arrays, etc.
- Annotation control: Similar to Jackson and Gson, it supports serialization and deserialization of annotation control fields.
Code Example
1. JSON to object
import ; public class FastJsonExample { public static void main(String[] args) { String json = "{"id":1,"name":"Xiao Ming"}"; User user = (json, ); (()); // Output: Xiao Ming } }
2. Object to JSON
User user = new User(); (3); ("Little Red"); String json = (user); (json); // Output: {"id":3,"name":"Little Red"}
Advanced features
Automatic hump to underline:
JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
Dynamic field analysis:
Map<String, Object> map = (json, );
Pros and cons
advantage | shortcoming |
---|---|
Extremely high performance and fast parsing speed | There have been controversies about historical security vulnerabilities |
Supports complex dynamic field analysis | Community activity is slightly less than Jackson and Gson |
Comprehensive functions, suitable for large-scale data processing scenarios | There are many configuration options and APIs, which are a bit complicated |
4. Using JsonPath: Quickly extract nested fields
Functional Features
- Efficient field extraction: Quickly extract nested fields through path expressions (similar to XPath).
- Strong flexibility: Support dynamic field and conditional filtering.
- Lightweight: Focus on field extraction, simple and clear functions.
Code Example
import ; public class JsonPathExample { public static void main(String[] args) { String json = """ { "store": { "book": [ {"title": "Book 1", "price": 10}, {"title": "Book 2", "price": 20} ] } } """; // Extract the title of the first book String title = (json, "$.[0].title"); (title); // Output: Book 1 // Extract all books for price List<Integer> prices = (json, "$.[*].price"); (prices); // Output: [10, 20] } }
Pros and cons
advantage | shortcoming |
---|---|
Field extraction is simple and efficient | Serialization and deserialization are not supported |
Strong dynamic field processing capability | Depend on JsonPath syntax |
Suitable for quick extraction of nested fields | Not suitable for full JSON conversion |
5. Use: Lightweight Tools
Functional Features
- Lightweight: The core is a tool class suitable for simple scenarios.
- Simple construction and parsing: Suitable for quickly creating JSON or extracting fields.
- General flexibility: Complex object mapping is not supported.
Code Example
import ; public class OrgJsonExample { public static void main(String[] args) { String json = "{"id":1,"name":"Zhang San"}"; // Extract fields JSONObject jsonObject = new JSONObject(json); (("name")); // Output: Zhang San // Construct JSON JSONObject newJson = new JSONObject(); ("id", 2); ("name", "Li Si"); (()); // Output: {"id":2,"name":"Li Si"} } }
Pros and cons
advantage | shortcoming |
---|---|
Lightweight, suitable for simple scenarios | Complex nested objects are not supported |
Simple to use and low learning cost | Simple function, poor scalability |
6. Manual parsing JSON: the most flexible
Functional Features
- Completely free: Do not rely on third-party libraries, parse JSON yourself.
- Dynamic processing: JSON suitable for irregular field structures.
- High code complexity: Suitable for special scenarios.
Code Example
import ; import ; import ; public class ManualParsing { public static void main(String[] args) throws Exception { String json = "{"id":1,"name":"Dynamic Field"}"; ObjectMapper objectMapper = new ObjectMapper(); Map<String, Object> map = (json, new TypeReference<Map<String, Object>>() {}); (("name")); // Output: Dynamic fields } }
Pros and cons
advantage | shortcoming |
---|---|
High flexibility, suitable for dynamic fields | High code complexity and not easy to maintain |
No dependency on third-party libraries | Lower performance and efficiency than professional JSON libraries |
Summarize
Finally, let me compare the advantages and disadvantages of the 6 methods mentioned in the article:
method | Applicable scenarios | advantage | shortcoming |
---|---|---|---|
Jackson | Enterprise-level projects, complex serialization and deserialization scenarios | Powerful function, excellent performance, and supports complex structures | Complex configuration and high learning curve |
Gson | Small and medium-sized projects, simple JSON conversion scenarios | Lightweight, easy to use | Limited functions, slightly inferior performance |
FastJSON | High performance requirements, dynamic analysis of large data volume | Extremely high performance and rich features | There was once a security vulnerability dispute, and the community support was slightly inferior Jackson |
JsonPath | Complex nested structure and dynamic field extraction scenarios | Simple syntax for field extraction and strong flexibility | Serialization and deserialization are not supported |
Quickly parse or construct JSON scenarios | Lightweight, suitable for simple scenarios | Single function, poor scalability | |
Manual analysis | Dynamic JSON or field unfixed scenarios | High degree of freedom and strong flexibility | Complex code, less efficient than professional tools |
There are thousands of tools, and the scene is the most important!
Only by choosing the right tool can you save time and effort, and take less pitfalls and fish more.
The above is the detailed content of six solutions for Java parsing JSON. For more information about Java parsing JSON, please pay attention to my other related articles!