Cases of object conversion completed by four commonly used JSON parsers

1. JSON basic format:

There are many excellent introductions in the blog JSON format. The introduction of the following blog is relatively complete in my opinion:

Portal: json basic data format


2. JSON parser introduction:

JSON parsers generally consist of two main functions: 解析和生成. The parsing function parses a JSON string into an in-memory data structure, typically an object, array, or collection of key-value pairs. The generate function converts the in-memory data structure into a JSON string.

Many programming languages ​​provide built-in JSON parsers and generators that can easily handle JSON data. For example, the JSON.parse() function in JavaScript is used to parse a JSON string and convert it into a JavaScript object; the JSON.stringify() function is used to convert a JavaScript object into a JSON string. Other programming languages ​​such as Python, Java, C#, etc. also provide similar functions.

Using the JSON parser, you can easily transfer and process data between different applications, especially for web applications and 客户端-服务器通信. Whether receiving JSON data from the web, or sending data to a remote server, a JSON parser is an essential tool.


3. Commonly used JSON parsers:

1. Jackson:

Jackson is a very popular JSON processing library that provides high-performance and flexible JSON parsing and generation functions. It can map JSON data into Java objects and convert Java objects into JSON format. Jackson also supports annotations, which can be used to further control the mapping relationship between JSON and Java objects.

首先,您需要在您的Java项目中添加Jackson库的依赖。如果使用Maven进行项目管理,
可以在pom.xml文件中添加以下依赖项:
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.12.3</version>
</dependency>
接下来,假设您有一个JSON字符串如下:
{
    
    
  "name": "John Doe",
  "age": 30,
  "email": "[email protected]"
}
现在,让我们看一下如何使用Jackson将该JSON字符串解析为Java对象,并将Java对象转换回JSON字符串:
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonExample {
    
    
    public static void main(String[] args) {
    
    
        String json = "{\"name\":\"John Doe\",\"age\":30,\"email\":\"[email protected]\"}";

        try {
    
    
            // 创建ObjectMapper对象
            ObjectMapper objectMapper = new ObjectMapper();

            // 解析JSON字符串为Java对象
            Person person = objectMapper.readValue(json, Person.class);
            System.out.println("Name: " + person.getName());
            System.out.println("Age: " + person.getAge());
            System.out.println("Email: " + person.getEmail());

            // 将Java对象转换为JSON字符串
            String jsonString = objectMapper.writeValueAsString(person);
            System.out.println("JSON: " + jsonString);
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
    }
}

class Person {
    
    
    private String name;
    private int age;
    private String email;

    // 必须有无参数的构造函数
    public Person() {
    
    
    }

    // getters 和 setters

    // name getter 和 setter
    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    // age getter 和 setter
    public int getAge() {
    
    
        return age;
    }

    public void setAge(int age) {
    
    
        this.age = age;
    }

    // email getter 和 setter
    public String getEmail() {
    
    
        return email;
    }

    public void setEmail(String email) {
    
    
        this.email = email;
    }
}

在上面的示例中,我们首先创建了一个ObjectMapper对象,它是Jackson库中用于解析和生成JSON的主要类。
然后,我们使用readValue()方法将JSON字符串解析为Person类的对象,
并使用writeValueAsString()方法将Person对象转换回JSON字符串。

请注意,Person类必须具有无参数的构造函数,并为每个属性提供相应的getter和setter方法,
以便Jackson可以正确地进行对象与JSON之间的映射。

以上是一个简单的示例,使用Jackson库进行JSON解析和生成的基本功能。
根据需要扩展和修改该示例以满足具体的业务逻辑。

2. Gson:

Gson is a simple and powerful JSON parsing library provided by Google. It can parse JSON strings into Java objects and convert Java objects into JSON strings. Gson provides many convenient APIs and annotations for configuring the details of the parsing and generation process.

首先,您需要在您的Java项目中添加Gson库的依赖。如果使用Maven进行项目管理,
可以在pom.xml文件中添加以下依赖项:
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.9</version>
</dependency>
接下来,假设您有一个JSON字符串如下:
{
    
    
  "name": "John Doe",
  "age": 30,
  "email": "[email protected]"
}

现在,让我们看一下如何使用Gson将该JSON字符串解析为Java对象,并将Java对象转换回JSON字符串:
import com.google.gson.Gson;

public class JsonExample {
    
    
    public static void main(String[] args) {
    
    
        String json = "{\"name\":\"John Doe\",\"age\":30,\"email\":\"[email protected]\"}";

        try {
    
    
            // 创建Gson对象
            Gson gson = new Gson();

            // 解析JSON字符串为Java对象
            Person person = gson.fromJson(json, Person.class);
            System.out.println("Name: " + person.getName());
            System.out.println("Age: " + person.getAge());
            System.out.println("Email: " + person.getEmail());

            // 将Java对象转换为JSON字符串
            String jsonString = gson.toJson(person);
            System.out.println("JSON: " + jsonString);
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
    }
}

class Person {
    
    
    private String name;
    private int age;
    private String email;

    // 必须有无参数的构造函数
    public Person() {
    
    
    }

    // getters 和 setters

    // name getter 和 setter
    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    // age getter 和 setter
    public int getAge() {
    
    
        return age;
    }

    public void setAge(int age) {
    
    
        this.age = age;
    }

    // email getter 和 setter
    public String getEmail() {
    
    
        return email;
    }

    public void setEmail(String email) {
    
    
        this.email = email;
    }
}

在上面的示例中,我们首先创建了一个Gson对象,它是Gson库中用于解析和生成JSON的主要类。
然后,我们使用fromJson()方法将JSON字符串解析为Person类的对象,并使用toJson()方法
将Person对象转换回JSON字符串。

3. JSON-B:

JSON-B (JSON Binding) is part of Java EE 8, which provides a standard JSON parsing and generation API. JSON-B provides annotations and configuration options to control the mapping between JSON and Java objects. JSON-B can be seamlessly integrated with Java's standard annotations and the JAX-RS (Java API for RESTful Web Services) framework.

4. org.json:

org.json is a simple JSON parser and generator provided by Java. It is included in the Java standard library and provides basic functions for parsing and generating JSON data. Although relatively simple in functionality, it is a lightweight and easy-to-use choice for simple JSON manipulation.

在Java标准库中的org.json包中,可以使用JSONObject和JSONArray类来解析和生成JSON数据。
以下是一个使用org.json实现JSON解析和生成的示例代码:
import org.json.JSONArray;
import org.json.JSONObject;

public class JsonExample {
    
    
    public static void main(String[] args) {
    
    
        String json = "{\"name\":\"John Doe\",\"age\":30,\"email\":\"[email protected]\"}";

        try {
    
    
            // 解析JSON字符串
            JSONObject jsonObject = new JSONObject(json);
            String name = jsonObject.getString("name");
            int age = jsonObject.getInt("age");
            String email = jsonObject.getString("email");

            System.out.println("Name: " + name);
            System.out.println("Age: " + age);
            System.out.println("Email: " + email);

            // 生成JSON字符串
            JSONObject newJsonObject = new JSONObject();
            newJsonObject.put("name", "Jane Smith");
            newJsonObject.put("age", 25);
            newJsonObject.put("email", "[email protected]");

            String newJsonString = newJsonObject.toString();
            System.out.println("JSON: " + newJsonString);
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
    }
}


这是一个简单的示例,展示了使用org.json进行JSON解析和生成的基本功能。
尽管功能相对简单,但对于简单的JSON操作,org.json是一个轻量级且易于使用的选择。
如果需求更加复杂,可能需要考虑使用其他功能更强大的JSON库,如Jackson或Gson。

Summarize

  • episode
    • 1. Create an ObjectMapper object
    • 2. Call the ObjectMapper readValuemethod to realize the JSON string as a Java object
    • 3. Call the ObjectMapper writeValueAsStringmethod to convert the Java object into a JSON string
  • Gson
    • 1. Create a Gson object
    • 2. Call fromJsonthe method of gson to realize the JSON string as a Java object
    • 3. Call the method of gson toJsonto realize the conversion of Java objects into JSON strings

  • A simple JSON parser and generator provided by org.json Java. It is included in the Java standard library and provides basic functions for parsing and generating JSON data. It can only parse and generate JSON strings, but cannot convert between java objects.

Each parser has its characteristics and applicable scenarios. You can choose a suitable JSON parser according to project requirements and personal preferences.


springboot integrated JSON supplement

In the springboot framework, there is no need to manually parse and generate and convert objects and json. springboot has helped us integrate through annotations.

Next, add the @ResponseBody annotation to the class annotated with @RestController, and use the @ResponseBody annotation on the specific method to explicitly instruct Spring to 返回的Java对象automatically convert to JSON.

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
//@ResponseBody
public class MyController {
    
    

    @GetMapping("/example")
    @ResponseBody
    public MyObject getExample() {
    
    
        // 返回的MyObject会自动转换为JSON
        return new MyObject();
    }
}

The following is by using the @RequestBody annotation on the method parameter, Spring Boot will automatically 接收到的JSON数据convert it to a Person object, and pass it in as a parameter of the method.

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {
    
    

    @PostMapping("/person")
    public Person createPerson(@RequestBody Person person) {
    
    
        // 在这里可以对person对象进行业务逻辑处理
        return person;
    }
}

Guess you like

Origin blog.csdn.net/qq_45973897/article/details/131190179