How does SpringBoot read JSON files?

Spring Boot has the ability to utilize the Jackson library to read JSON files.

Firstly, you need to add the Jackson library dependency in the pom.xml file.

<dependencies>
    <!-- 添加Jackson库依赖 -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
    </dependency>
</dependencies>

Then, in the code of Spring Boot, use the ObjectMapper class to read the JSON file. Assume there is a file named data.json with the following content:

{
  "name": "John Doe",
  "age": 30,
  "email": "john.doe@example.com"
}

You can use the following code to read the JSON file:

import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.io.IOException;

public class JsonReader {

    public static void main(String[] args) {
        ObjectMapper objectMapper = new ObjectMapper();

        try {
            // 读取JSON文件
            File file = new File("data.json");

            // 将JSON文件转换为Java对象
            User user = objectMapper.readValue(file, User.class);

            // 打印Java对象
            System.out.println(user);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In the code above, we used the readValue() method of the ObjectMapper to convert a JSON file into a Java object. In this example, we created a User class to represent the structure of the JSON file.

public class User {
    private String name;
    private int age;
    private String email;

    // getter和setter方法

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", email='" + email + '\'' +
                '}';
    }
}

Finally, you can run the code to read the JSON file and convert it into a Java object.

bannerAds