由于数据库目前只有表,还未填充数据,因此计划通过导入 Json 文件中的数据,插入到后台数据库,供开发测试。本文主要讲解基于 SpringBoot 项目如何将本地 Json 文件导入到后台数据库。

背景

数据库中有一张名为 product 的表,表创建信息如下:

CREATE TABLE `product` (`productId` int(20) NOT NULL,`productName` varchar(100) DEFAULT NULL,`discontinued` varchar(10) DEFAULT NULL,`unitsInStock` int(10) DEFAULT NULL,`unitPrice` double(10,2) NOT NULL,PRIMARY KEY (`productId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

SpringBoot 项目中关于该表的定义都已实现,包括实现类,mapper 接口,映射文件和 controller 文件。

关于 product 表的数据存放在 Json 文件中,格式如下:

[{"ProductID": 1,"ProductName": "Chai","UnitPrice": 18,"UnitsInStock": 39,"Discontinued": false
}, {"ProductID": 2,"ProductName": "Chang","UnitPrice": 19,"UnitsInStock": 17,"Discontinued": false
}, {.....}
]

将 json 文件存放到项目中,文件结构如下:

接下来我们进行数据读取和数据库存储。

导入依赖

使用 fastjson 用于将 String 类型的数据转换为 Json。

<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.47</version>
</dependency>
<dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.4</version>
</dependency>

实现方式

方式一

在 @SpringBootTest 注解修饰的类中进行测试,

import org.springframework.util.ResourceUtils;
import org.apache.commons.io.FileUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;import com.msdn.mapper.ProductMapper;
import com.msdn.pojo.Product;@SpringBootTest
class SpringbootStudy05ApplicationTests {@AutowiredProductMapper mapper;@Testvoid getData() throws IOException {File jsonFile = ResourceUtils.getFile("classpath:static/data.json");//数据读取String json = FileUtils.readFileToString(jsonFile);//String字符串转换为Json数组JSONArray jsonArray = JSON.parseArray(json);//遍历每一个json对象,将内容存放到Product对象中for (Object obj : jsonArray) {JSONObject jobj = (JSONObject) obj;int productId = Integer.parseInt(jobj.getString("ProductID"));String productName = jobj.getString("ProductName");String discontinued = jobj.getString("Discontinued");double unitPrice = Double.parseDouble(jobj.getString("UnitPrice"));int unitsInStock = Integer.parseInt(jobj.getString("UnitsInStock"));Product product = new Product();product.setProductId(productId);product.setProductName(productName);product.setDiscontinued(discontinued);product.setUnitPrice(unitPrice);product.setUnitsInStock(unitsInStock);//数据插入mapper.save(product);}}
}

方式二

新建一个 Service 类 JsonUtilService

@Service
public class JsonUtilService {@Value("classpath:static/data.json")public Resource resource;public String getData(){try {File file = resource.getFile();String jsonData = this.jsonRead(file);return jsonData;} catch (Exception e) {return null;}}private String jsonRead(File file) throws IOException{BufferedReader reader = null;StringBuilder buffer = new StringBuilder();reader = new BufferedReader(new FileReader(file));String line = "";while ((line = reader.readLine()) != null){buffer.append(line);}reader.close();return buffer.toString();}
}

然后注入到测试类中。

@SpringBootTest
class SpringbootStudy05ApplicationTests {@AutowiredJsonUtilService service;@AutowiredProductMapper mapper;@Testvoid getData() throws IOException {String value = service.getData();JSONArray jsonArray = JSONObject.parseArray(value);for (Object obj : jsonArray) {JSONObject jobj = (JSONObject) obj;int productId = Integer.parseInt(jobj.getString("ProductID"));String productName = jobj.getString("ProductName");String discontinued = jobj.getString("Discontinued");double unitPrice = Double.parseDouble(jobj.getString("UnitPrice"));int unitsInStock = Integer.parseInt(jobj.getString("UnitsInStock"));Product product = new Product();product.setProductId(productId);product.setProductName(productName);product.setDiscontinued(discontinued);product.setUnitPrice(unitPrice);product.setUnitsInStock(unitsInStock);mapper.save(product);}}
}

总结

注意:这两种方式打成jar包很有可能读取不到数据。解决方案:修改 Json 文件的读取方式,代码如下:

public static String getFileJson() throws IOException {ClassPathResource classPathResource = new ClassPathResource("static/data.json");byte[]  bytes= FileCopyUtils.copyToByteArray(classPathResource.getInputStream());rturn new String(bytes);
}

参考文献

SpringBoot项目读取json格式文件配置

Java多种读文件方式

grafana导入json文件没有数据_基于SpringBoot将Json数据导入到数据库相关推荐

  1. java 金数据推送数据_基于JAVA的黄金数据接口调用代码实例

    代码描述:基于JAVA的黄金数据接口调用代码实例 接口地址:http://www.juhe.cn/docs/api/id/29 1.[代码][Java]代码 import java.io.Buffer ...

  2. oracle 导入sql文件 汉字乱码_将现有的sql脚本导入 Oracle 数据库,中文乱码问题...

    将现有的sql 脚本导入 Oracle数据库 比如 在windows 系统下,可以写一个 bat 来实现直接导入 如:bat 中的内容如下,logs.log 将会记录执行日志 sqlplus user ...

  3. wps解析json数据_浏览器处理2500MB JSON文件的解析与绘图问题(实践分享,非战斗人员请忽略)...

    最近在做一个浏览器画数据图的任务. 任务其实很简单,浏览器通过ajax请求拿到服务端已经生成好的json文件,然后在前端浏览器绘制相应的折线图,饼状图等. 很丑陋的dataflow 起初我的做法 le ...

  4. 大数据实时处理-基于Spark的大数据实时处理及应用技术培训

    随着互联网.移动互联网和物联网的发展,我们已经切实地迎来了一个大数据 的时代.大 数据是指无法在一定时间内用常规软件工具对其内容进行抓取.管理和处理的数据集合,对大数据的分析已经成为一个非常重要且紧迫 ...

  5. 【LSTM时间序列数据】基于matlab LSTM时间序列数据预测【含Matlab源码 1949期】

    ⛄一.获取代码方式 获取代码方式1: 完整代码已上传我的资源:[LSTM时间序列数据]基于matlab LSTM时间序列数据预测[含Matlab源码 1949期] 获取代码方式2: 付费专栏Matla ...

  6. 基于Springboot+vue电影院会员管理系统(源代码+数据库+文档)025

    部分代码地址 https://gitee.com/ynwynwyn/cinema-public 基于Springboot+vue电影院会员管理系统(源代码+数据库+文档) 一.系统介绍 cinema项 ...

  7. 基于Springboot的社区论坛系统(源代码+数据库)055

    部分代码地址 https://gitee.com/ynwynwy/forum-public 基于Springboot的社区论坛系统(源代码+数据库) 一.系统介绍 前台: 话题列表,搜索话题,发布话题 ...

  8. 基于springboot的酒店预订管理系统(源代码+数据库+10000字文档) 002

    代码地址 https://gitee.com/ynwynwyn/spring-boot-hotel-manager-public 基于springboot的酒店预订管理系统(源代码+数据库+10000 ...

  9. 基于springboot+vue的房屋租赁统(源代码+数据库)071

    部分代码地址 https://gitee.com/ynwynwyn/houserentVuePublic 基于springboot+vue的房屋租赁系统(源代码+数据库) 一.系统介绍 本项目前后端分 ...

  10. 基于Springboot + Thymeleaf 的招聘网站(源代码+数据库) 026

    部分代码地址 https://gitee.com/ynwynwyn/springboot-recruit-public 基于Springboot + Thymeleaf 的招聘网站(源代码+数据库) ...

最新文章

  1. Git环境搭建与基本使用方法
  2. 学python有哪些书推荐-Python 有哪些入门学习方法和值得推荐的经典教材?
  3. 代码大全阅读笔记02
  4. CentOS7下搭建LAMP+FreeRadius+Daloradius Web管理
  5. python动态生成数据库表_使用Python创建MySQL数据库实现字段动态添加以及动态的插入数据...
  6. hibernate中表的复合主键映射表
  7. [Shder]物体溶解效果
  8. 百度积极回应阿波龙项目不实报道;半数开发者认为学习新语言很困难;腾讯在长沙建立首个智慧产业总部……...
  9. oracle创建多个游标,Oracle——游标的创建和使用
  10. 大数据之HBase部署
  11. [唐诗]正月十五日夜-苏味道
  12. (77)Vivado设置伪路径约束
  13. mysql集群方案,保准看明白!
  14. 微信小程序点餐系统需求分析与建模
  15. 总线通信协议-PCIe
  16. 2010计算机一级选择题,计算机一级考试选择题题库(2010年最新版)
  17. 《Java程序设计》期末复习资料
  18. 基于HTML+CSS+JavaScript仿华为手机电子商城
  19. Tina-TI——小巧好用又高效的原理图仿真软件
  20. 弘辽科技:直通车成交率多少正常?如何提高成交率?

热门文章

  1. 成为一个优秀网络工程师的条件
  2. Tomcat环境设置
  3. 37.go struct 结构
  4. 1.单进程SAPI生命周期
  5. 17.卷2(进程间通信)---后记
  6. 38. 后台模块开发(3)
  7. 河南计算机考试照片要求,2020年河南地区国考照片处理工具使用流程详解(2)
  8. matlab 切比雪夫逼近,切比雪夫等波纹逼近.PDF
  9. css中的外边距合并时垂直方向上的普通流相邻元素间
  10. Ubuntu上,如何成功的安装pygrib