introduction
In modern Java development, JSON (JavaScript Object Notation) is a lightweight data exchange format and is widely used in front-end interaction, configuration file reading, and various data storage scenarios. Proficient in the methods of parsing JSON and generating JSON strings in Java are key skills that every developer must have. This article will conduct in-depth analysis of common libraries and corresponding implementation methods to help you easily control JSON data processing.
1. Use the Jackson library to perform JSON operations
1. Introduce dependencies
If using the Maven project,Add the following dependencies to the file:
<dependency> <groupId></groupId> <artifactId>jackson-databind</artifactId> <version>2.14.2</version> <!-- Versions that can be adjusted as needed --> </dependency>
2. Parsing JSON strings as Java objects
Suppose we have the following simple JSON string:{"name":"Zhang San","age":20,"hobbies":["Reading","Sport"]}
, and the corresponding Java classesPerson
:
import ; public class JacksonParseExample { public static void main(String[] args) throws Exception { String json = "{\"name\":\"Zhang San\",\"age\":20,\"hobbies\":[\"read\",\"sports\"]}"; ObjectMapper mapper = new ObjectMapper(); Person person = (json, ); (()); // Output: Zhang San } } class Person { private String name; private int age; private String[] hobbies; // Omit the getter and setter methods}
ObjectMapper
Classes are the core of Jackson.readValue
Methods are based on the specified target class, automatically maps the JSON string to Java object instance, accurately parses each field value, and completes data conversion.
3. Generate JSON string
import ; public class JacksonGenerateExample { public static void main(String[] args) throws Exception { Person person = new Person(); ("Li Si"); (25); (new String[]{"music", "painting"}); ObjectMapper mapper = new ObjectMapper(); String json = (person); (json); // Output: {"name":"Li Si","age":25,"hobbies":["Music","Painting"]} } }
Call the writeValueAsString method, and the ObjectMapper serializes the Java object person into a standard JSON format string, ready for network transmission or storage, which is convenient, fast and standardized.
2. JSON processing based on Gson library
1. Import the Gson library
For Maven projects, add dependencies:
<dependency> <groupId></groupId> <artifactId>gson</artifactId> <version>2.10.1</version> <!-- Adjust according to actual --> </dependency>
2. Parsing JSON
Use the samePerson
Class example, parsing JSON is as follows
import ; public class GsonParseExample { public static void main(String[] args) { String json = "{\"name\":\"Wang Wu",\"age\":30,\"hobbies\":[\"travel\",\"photography\"]}"; Gson gson = new Gson(); Person person = (json, ); (()); // Output: Wang Wu } }
Gson
ClassicfromJson
Efficient function parsing JSON, seamless fillingPerson
Objects are also freely dealing with complex nested structures and accurately extract data.
3. Generate JSON string
import ; public class GsonGenerateExample { public static void main(String[] args) { Person person = new Person(); ("Zhao Liu"); (35); (new String[]{"calligraphy", "Play Chess"}); Gson gson = new Gson(); String json = (person); (json); // Output: {"name":"Zhao Liu","age":35,"hobbies":["Calligraphy","chess"]} } }
toJson
The method willperson
The object is quickly converted into JSON strings, with concise code, compact and clear output format, and is suitable for a variety of data transmission needs.
3. FastJSON application
1. Introducing FastJSON
Maven dependency configuration:
<dependency> <groupId></groupId> <artifactId>fastjson</artifactId> <version>2.0.33</version> <!-- Pay attention to version adaptation --> </dependency>
2. Parsing JSON
import ; public class FastJSONParseExample { public static void main(String[] args) { String json = "{\"name\":\"Sun Qi",\"age\":40,\"hobbies\":[\"cooking\",\"manual\"]}"; Person person = (json, ); (()); // Output: Sun Qi } }
FastJSON
ofparseObject
The method is known for its high performance, quickly parsing JSON as a Java object, and has significant advantages when processing large-scale data analysis, and can efficiently meet high-concurrency business scenarios.
3. Generate JSON
import ; public class FastJSONGenerateExample { public static void main(String[] args) { Person person = new Person(); ("Battle of the Week"); (45); (new String[]{"Dance", "Sing"}); String json = (person); (json); // Output: {"age":45,"hobbies":["Dancing","singing"],"name":"Battle"} } }
toJSONString implements extremely fast conversion of object to JSON strings, and generates string formats in neat formats. It frequently appears in distributed systems and big data processing scenarios that pursue extreme performance to ensure efficient and smooth data flow.
Whether you choose Jackson, Gson or FastJSON, you can achieve flexible interchange between JSON and Java data based on project characteristics. Small-scale projects focus on simplicity and availability, Gson or FastJSON is light and flexible; large enterprise-level applications, Jackson's rich functions and stability are more capable of supporting the richness of complex business logic and strict performance requirements. Developers make decisions on demand and implement them accurately, and they will be able to be at ease in the ocean of JSON data.
The above is the detailed content of a comprehensive guide to parsing JSON and generating JSON strings in Java. For more information about parsing JSON and generating JSON strings in Java, please pay attention to my other related articles!