搜索
首页Javajava教程SpringBoot怎么读取资源目录中JSON文件

SpringBoot怎么读取资源目录中JSON文件

May 16, 2023 pm 01:25 PM
jsonspringboot

思路

使用Spring的ResourceUtils读取资源目录下的json文件。

使用common-io将读取的文件转化为json字符串。

使用fastjson将json字符串反序列为对象。

示例

SpringBoot怎么读取资源目录中JSON文件

1.Maven依赖

pom.xml,主要是common-io、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资源文件

notice.json,简单列举要使用json内容。

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

3.读取json的Service

3.1.定义接口

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.实现接口

这里可以说是本文的核心部分了,具体可以看代码中的实现,通过ResourceUtils读取notice.json这个json文件,通过common-io的FileUtils转化文件为json字符串,通过fastjson的JSON反序列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.测试接口

编写一个简单的集成测试,将上述编写的Service注入,执行方法,打印执行结果。

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());
    }
}

SpringBoot怎么读取资源目录中JSON文件

可以看到,可以正常地输出json文件中的内容,说明我们的程序是正确的。

以上是SpringBoot怎么读取资源目录中JSON文件的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:亿速云。如有侵权,请联系admin@php.cn删除
Java仍然是基于新功能的好语言吗?Java仍然是基于新功能的好语言吗?May 12, 2025 am 12:12 AM

Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

是什么使Java很棒?关键特征和好处是什么使Java很棒?关键特征和好处May 12, 2025 am 12:11 AM

Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

前5个Java功能:示例和解释前5个Java功能:示例和解释May 12, 2025 am 12:09 AM

Java的五大特色是多态性、Lambda表达式、StreamsAPI、泛型和异常处理。1.多态性让不同类的对象可以作为共同基类的对象使用。2.Lambda表达式使代码更简洁,特别适合处理集合和流。3.StreamsAPI高效处理大数据集,支持声明式操作。4.泛型提供类型安全和重用性,编译时捕获类型错误。5.异常处理帮助优雅处理错误,编写可靠软件。

Java的最高功能如何影响性能和可伸缩性?Java的最高功能如何影响性能和可伸缩性?May 12, 2025 am 12:08 AM

java'stopfeatureSnificallyEnhanceItsperFormanCeanDscalability.1)对象 - 方向 - incipleslike-polymormormormormormormormormormormormormorableablefleandibleandscalablecode.2)garbageCollectionAutoctionAutoctionAutoctionAutoctionAutoctionautomorymanatesmemorymanateMmanateMmanateMmanagementButCancausElatenceiss.3)

JVM内部:深入Java虚拟机JVM内部:深入Java虚拟机May 12, 2025 am 12:07 AM

JVM的核心组件包括ClassLoader、RuntimeDataArea和ExecutionEngine。1)ClassLoader负责加载、链接和初始化类和接口。2)RuntimeDataArea包含MethodArea、Heap、Stack、PCRegister和NativeMethodStacks。3)ExecutionEngine由Interpreter、JITCompiler和GarbageCollector组成,负责bytecode的执行和优化。

什么是使Java安全安全的功能?什么是使Java安全安全的功能?May 11, 2025 am 12:07 AM

Java'ssafetyandsecurityarebolsteredby:1)strongtyping,whichpreventstype-relatederrors;2)automaticmemorymanagementviagarbagecollection,reducingmemory-relatedvulnerabilities;3)sandboxing,isolatingcodefromthesystem;and4)robustexceptionhandling,ensuringgr

必不可少的Java功能:增强您的编码技巧必不可少的Java功能:增强您的编码技巧May 11, 2025 am 12:07 AM

javaoffersseveralkeyfeaturesthatenhancecodingskills:1)对象 - 方向 - 方向上的贝利奥洛夫夫人 - 启动worldentities

JVM最完整的指南JVM最完整的指南May 11, 2025 am 12:06 AM

thejvmisacrucialcomponentthatrunsjavacodebytranslatingitolachine特定建筑,影响性能,安全性和便携性。1)theclassloaderloader,links andinitializesClasses.2)executionEccutionEngineExecutionEngineExecutionEngineExecuteByteCuteByteCuteByteCuteBytecuteBytecuteByteCuteByteCuteByteCuteBytecuteByteCodeNinstRonctientions.3)Memo.3)Memo

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中