java/SpringBoot项目将json文件内容写入数据库
大致步骤:
添加依赖Jackson
->利用ObjectMapper的readValue读取json文件,转为Map<String,Object>对象
->读取过后对处理map,分别按需求进行取值,添加进数据库即可
那么开始操作!
1.添加依赖包
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.8</version>
</dependency>
2.实体,构造和get/set方法自然不用多说,按需设置
3.写好数据库具体基础添加方法
service接口->impl实现类->调用的mapper数据库方法->mybatis的核心sql语句*mapper.xml文件!
4.操作json文件也是这里的核心代码(sss()是测试方法)
emmmm…具体步骤看注释!
public boolean sss(){
ObjectMapper mapper = new ObjectMapper();//实例一个ObjectMapper
try {
Map<String,Object> map = mapper.readValue(
new File("E:\\WorkSpace\\msg\\src\\main\\resources\\json\\hotelList\\hotellist_cityId1.json"),//使用mapper.readValue,读取json文件
new TypeReference<Map<String, Object>>(){});
// public <T> T readValue(File src, TypeReference valueTypeRef)调用这个,暂时猜测是,前者是具体文件,后者是需要加工成的参考类型,这里是通过jsonFactory处理为map文件
//取得需要的hotels,(这里hotelList就是整个json文件最外成的key,value就是hotels但也是map,强转为list就可进行遍历。)
List<Hotel> hotels = (List<Hotel>) map.get("HotelList");
Hotel hotel = new Hotel();//实例化实体对象
int inser=0;//计算添加了多少条
for (int i=0;i<hotels.size();i++){
Map h = (Map) hotels.get(i);
//封装实体
hotel.setCityID(h.get("CityID")==null?null:(Integer) h.get("CityID"));//添加三元运算,主要是判断是否为空,为空就写null,不为空就转为需要的类型
hotel.setNameChn(h.get("NameChn")==null?null:h.get("NameChn").toString());
hotel.setNameEng(h.get("NameEng")==null?null:h.get("NameEng").toString());
hotel.setAddress(h.get("Address")==null?null:h.get("Address").toString());
hotel.setAddressEng(h.get("AddressEng")==null?null:h.get("AddressEng").toString());
hotel.setStar(h.get("star")==null?null:(Integer) h.get("star"));
hotel.setIntroduction(h.get("Introduction")==null?null:h.get("Introduction").toString());
hotel.setLatitude(h.get("Latitude")==null?null:h.get("Latitude").toString());
hotel.setLongitude(h.get("Latitude")==null?null:h.get("Latitude").toString());
hotel.setCommentScore(h.get("CommentScore")==null?null:Double.parseDouble( h.get("CommentScore").toString()));//intger装doouble 要先转为string
hotel.setRemarks(h.get("Remarks")==null?null:h.get("Remarks").toString());
insert(hotel);//添加进数据库
inser ++;
}
System.out.println("添加条数:"+inser);
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
5.测试,调用即可
@Test
public void contextLoads() {
hotelService.sss();
}
注意:
在写测试的时候犯了一个错,导致空指针异常。
错误: 之前是通过HotelServiceImpl hotelService1=new HotelServiceImpl();然后直接调hotelService1.sss()方法,就导致了关于映射mybatis数据库方法,的mapper/DAO接口的 对象一直报空指针!
解决: 在service中多写一个方法,impl中sss()作实现,测试实例就是用:
@Resource
private HotelService hotelService;
测试:
hotelService.sss();
ok!终于解决一个空指针异常!
6.其实还有起他的方法,这里就不多说了。。。
这里是同事用的另一种:https://blog.csdn.net/qq_43419029/article/details/87857039