search
HomeJavajavaTutorialHow does SpringBoot read JSON files in the resource directory?

Idea

Use Spring's ResourceUtils to read the json file in the resource directory.

Use common-io to convert the read file into a json string.

Use fastjson to deserialize json strings into objects.

Example

How does SpringBoot read JSON files in the resource directory?

1.Maven depends on

pom.xml, mainly the introduction of common-io and fastjson.

<!-- 资源目录资源文件读取 -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.11.0</version>
        </dependency>

        <!-- 反序列化json字符串 -->
        <dependency>
            <groupId>com.alibaba.fastjson2</groupId>
            <artifactId>fastjson2</artifactId>
            <version>2.0.14</version>
        </dependency>

2.json resource file

notice.json, simply list the json content to be used.

[
  {
    "title": "新功能xxx上线",
    "content": "支持xxx"
  },
  {
    "title": "旧功能xxx下线",
    "content": "不支持xxx"
  }
]

3. Read json Service

3.1. Define the interface

package com.example.springbootjson.service;

import com.example.springbootjson.domain.NoticeInfo;

import java.io.IOException;
import java.util.List;

/**
 * @author hongcunlin
 */
public interface NoticeService {
    /**
     * 获取公告
     *
     * @return 公告
     * @throws IOException 文件
     */
    List<NoticeInfo> getNoticeInfoList() throws IOException;
}

3.2. Implement the interface

This can be said to be the core part of this article , you can see the implementation in the code for details, read the notice.json json file through ResourceUtils, convert the file into a json string through common-io's FileUtils, and deserialize the json object through fastjson's JSON.

package com.example.springbootjson.service.impl;

import com.alibaba.fastjson2.JSON;
import com.example.springbootjson.domain.NoticeInfo;
import com.example.springbootjson.service.NoticeService;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @author hongcunlin
 */
@Service
public class NoticeServiceImpl implements NoticeService {

    @Override
    public List<NoticeInfo> getNoticeInfoList() throws IOException {
        File file = ResourceUtils.getFile("classpath:notice.json");
        String json = FileUtils.readFileToString(file, "UTF-8");
        List<NoticeInfo> noticeInfoList = JSON.parseArray(json, NoticeInfo.class);
        return noticeInfoList;
    }
}

4. Test interface

Write a simple integration test, inject the Service written above, execute the method, and print the execution results.

package com.example.springbootjson;

import com.example.springbootjson.service.NoticeService;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;
import java.io.IOException;

@SpringBootTest
class SpringbootJsonApplicationTests {
    @Resource
    private NoticeService noticeService;

    @Test
    void contextLoads() throws IOException {
        System.out.println(noticeService.getNoticeInfoList());
    }
}

How does SpringBoot read JSON files in the resource directory?

You can see that the content in the json file can be output normally, indicating that our program is correct.

The above is the detailed content of How does SpringBoot read JSON files in the resource directory?. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor