How to use FastJSON in the Java backend to process the JSON data sent by the frontend and convert it into a collection!

You can follow these steps:

1. First, make sure you have imported the FastJSON library. You can import FastJSON into your Maven project by adding the following dependencies:

```xml

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.76</version> <!-- 使用合适的版本号 -->
</dependency>


```

2. In your backend code, use FastJSON for data parsing and conversion:

```java

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import java.util.List;

public class JsonProcessingExample {

    public static void main(String[] args) {
        String jsonData = "[{\"department_id\":1,\"room_id\":2,\"doctor_id\":117,\"inquiry_time\":\"2023-08-10T16:00:00.000Z\",\"quantity\":\"78\",\"sign\":\"下午\"}]";

        // 使用 FastJSON 解析 JSON 数据
        JSONArray jsonArray = JSON.parseArray(jsonData);

        // 将 JSON 数据转换为 List 集合
        List<AppointmentRequest> appointmentRequests = jsonArray.toJavaList(AppointmentRequest.class);

        // 处理集合中的数据
        for (AppointmentRequest request : appointmentRequests) {
            System.out.println(request);
        }
    }
}

class AppointmentRequest {
    private int department_id;
    private int room_id;
    private int doctor_id;
    private String inquiry_time;
    private String quantity;
    private String sign;

    // 添加对应的构造函数、getter和setter方法

    @Override
    public String toString() {
        return "AppointmentRequest{" +
                "department_id=" + department_id +
                ", room_id=" + room_id +
                ", doctor_id=" + doctor_id +
                ", inquiry_time='" + inquiry_time + '\'' +
                ", quantity='" + quantity + '\'' +
                ", sign='" + sign + '\'' +
                '}';
    }
}


```

In the above example, the JSON data is first parsed into a FastJSON `JSONArray` object by `JSON.parseArray(jsonData)`. Then, use the `toJavaList` method to convert the `JSONArray` to a `List` collection containing `AppointmentRequest` objects.

In this way, you can process the JSON data sent from the front end by iterating through the `appointmentRequests` collection.

Please note that you need to make adjustments according to your project structure and business logic in practical applications.

Guess you like

Origin blog.csdn.net/qq_58647634/article/details/132182793