Java調(diào)用接口如何獲取json數(shù)據(jù)解析后保存到數(shù)據(jù)庫
Java調(diào)用接口獲取json數(shù)據(jù)保存到數(shù)據(jù)庫
今天給大家?guī)硪粋€(gè)調(diào)用接口,來獲取數(shù)據(jù)解析后再保存到數(shù)據(jù)庫中的業(yè)務(wù),業(yè)務(wù)中的Mapper和實(shí)體類我就不在這里寫了,相信大家都會(huì)寫新增的SQL和定義實(shí)體類。
下面是我寫的業(yè)務(wù)代碼,有什么建議可以給我評(píng)論留言。
1.在yml文件中配置自己定義的接口URL
? ? //自己定義的JSON接口URL ? ? blacklist_data_url: 接口URL
2.在Controller中添加請(qǐng)求方法和路徑
? ? /** ? ? ?* @Title: 查詢 ? ? ?* @Description: 查詢車輛的記錄 ? ? ?* @Author: 半度納 ? ? ?* @Date: 2022/9/27 17:33 ? ? ?*/ ? ? @GetMapping("/Blacklist") ? ? public void selectBlacklist(){ ? ? ? ? boolean a = imBuBlacklistService.selectBlacklist();//調(diào)用業(yè)務(wù)層方法 ? ? }
3.在Service中添加方法
?? ?/** ? ? ?* @Title: 查詢 ? ? ?* @Description: 查詢車輛的記錄 ? ? ?* @Author: 半度納 ? ? ?* @Date: 2022/9/27 17:33 ? ? ?* @return ? ? ?*/ ? ? public boolean selectBlacklist();//返回值類型沒要求
4.在ServiceImpl中實(shí)現(xiàn)方法
?? ?import cn.hutool.json.JSONArray; ? ? import cn.hutool.json.JSONObject; ? ? import com.alibaba.fastjson2.JSON; ? ? ? ? @Value("${blacklist_data_url}") ? ? public String blacklist_data_url;//接口URL ? ? ?? ?/** ? ? ?* @Title: 查詢 ? ? ?* @Description: 查詢車輛的記錄 ? ? ?* @Author: 半度納 ? ? ?* @Date: 2022/9/27 17:33 ? ? ?* @return ? ? ?*/ ? ? @Override ? ? public boolean selectBlacklist() { ? ? ? ? //獲取的JSON接口數(shù)據(jù)(在輸出測(cè)試時(shí)sendGet方法可能會(huì)自動(dòng)輸出,具體需看底層代碼) ? ? ? ? String list= HttpUtils.sendGet(blacklist_data_url); ? ? ? ? JSONObject j = JSON.parseObject(list);//將獲取的JSON數(shù)據(jù)存儲(chǔ)到變量中 ? ? ? ? if(j.getBoolean("success")){//獲取success判斷是否為空 ? ? ? ? ? ? JSONObject jsonData = j.getJSONObject("body");//解析JSON的body ? ? ? ? ?? ?JSONArray jsonArray = jsonData.getJSONArray("data");//解析JSON的data數(shù)據(jù) ? ? ? ? ?? ?JSONObject row = null;//定義一個(gè)空變量 ? ? ? ? ?? ?ImBuBlacklist buBlacklist=new ImBuBlacklist();//new一個(gè)實(shí)體類用來接收數(shù)據(jù) ? ? ? ? ?? ?for (int y = 0; y < jsonArray.size(); ++y) {//循環(huán)將JSON數(shù)據(jù)存儲(chǔ)到數(shù)據(jù)庫中 ? ? ? ? ? ? ?? ?buBlacklist = new ImBuBlacklist();//new一個(gè)實(shí)體類存儲(chǔ)數(shù)據(jù) ? ? ? ? ? ? ?? ?row = jsonArray.getJSONObject(y);//獲取數(shù)組中的數(shù)據(jù) ? ? ? ? ? ??? ??? ?//設(shè)置獲取到的JSON號(hào)牌號(hào)碼到實(shí)體類的相同字段中 ? ? ? ? ? ? ?? ?buBlacklist.setPlateNumber(row.getString("mechanicalNumber")); ? ? ? ? ? ? ?? ?//設(shè)置獲取到的JSON車輛類型到實(shí)體類的相同字段中 ? ? ? ? ? ? ?? ?buBlacklist.setVehicleType(row.getString("machType")); ? ? ? ? ? ? ?? ?//設(shè)置獲取到的JSON檢查日期到實(shí)體類的相同字段中 ? ? ? ? ? ??? ??? ?buBlacklist.setExamineDate(row.getDate("createDate")); ? ? ? ? ? ? ?? ?//設(shè)置獲取到的JSON檢查地點(diǎn)到實(shí)體類的相同字段中 ? ? ? ? ? ? ?? ?buBlacklist.setExamineAddress(row.getString("machineAddr")); ? ? ? ? ? ? ?? ?//設(shè)置獲取到的JSON違規(guī)行為到實(shí)體類的相同字段中 ? ? ? ? ? ? ?? ?buBlacklist.setIllegalBehavior(row.getString("joinTheBlacklistReason")); ? ? ? ? ? ? ?? ?//設(shè)置獲取到的JSON黑名單類型到實(shí)體類的相同字段中 ? ? ? ? ? ? ?? ?buBlacklist.setBlacklistType(row.getInteger("violations")); ? ? ? ? ? ? ?? ?//通過mapper的新增方法,把實(shí)體類中的JSON數(shù)據(jù)存到數(shù)據(jù)庫中 ? ? ? ? ? ? ?? ?imBuBlacklistMapper.insertImBuBlacklist(buBlacklist); ? ? ? ? ?? ?} ? ? ? ? ?? ?return true;//自己定義的返回值(沒有用) ? ? ? ? }else{ ? ? ? ? ? ? return false; ? ? ? ? } ? ? }
調(diào)用接口,解析Json字符串并存入數(shù)據(jù)庫
通過api接口獲取json字符串
通過get(httpGet)請(qǐng)求獲取接口數(shù)據(jù),使用HttpClient基本分六步:
- 創(chuàng)建HttpClient實(shí)例
- 創(chuàng)建某種連接方法的實(shí)例
- 調(diào)用HttpClient實(shí)例的execute方法來執(zhí)行請(qǐng)求方法
- 讀取response
- 釋放連接,無論執(zhí)行方法是否成功
//創(chuàng)建httpClient實(shí)例 CloseableHttpClient client = HttpClients.createDefault(); //汽車之家api接口 String apiPath = "https://www.autohome.com.cn/ashx/index/GetHomeFindCar.ashx"; //創(chuàng)建get方法請(qǐng)求實(shí)例 HttpGet httpGet = new HttpGet(apiPath); //添加表頭,text/xml表示XML格式 httpGet.addHeader("content-type","text/xml"); //調(diào)用HttpClient實(shí)例執(zhí)行GET實(shí)例,返回response HttpResponse response = client.execute(httpGet); //解析response,這個(gè)過程主要取決于獲取的json格式,是一個(gè)對(duì)象還是一個(gè)數(shù)組,放到后面詳解 String result = EntityUtils.toString(response.getEntity()); //釋放連接 response.close(); client.close();
其中我們可以對(duì)response的狀態(tài)(state)進(jìn)行判斷,驗(yàn)證是否獲取數(shù)據(jù). 頁面請(qǐng)求的狀態(tài)值,分別有:200請(qǐng)求成功、303重定向、400請(qǐng)求錯(cuò)誤、401未授權(quán)、403禁止訪問、404文件未找到、500服務(wù)器錯(cuò)誤.
(HttpStatus.OK = 200;HttpStatus.BAD_REQUEST = 400;HttpStatus.FORBIDDEN = 403;HttpStatus.NOT_FOUND = 404;HttpStatus.SERVICE_UNAVAILABLE =500)
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { String result = EntityUtils.toString(response.getEntity());//解析response }//getStatusLine()方法返回保存請(qǐng)求狀態(tài)的StatusLine對(duì)象,getStatusCode()獲取狀態(tài)碼
使用JSONArray和JSONObject解析json字符串
在解析json字符串之前,我們一定要先確定json字符串的格式,針對(duì)不同的格式要使用不同的解析方法這里列舉了一些常見的json字符串格式
例如:數(shù)值,字符串,數(shù)組,對(duì)象數(shù)組或數(shù)組對(duì)象.重點(diǎn)就在于花括號(hào)和中括號(hào)的使用,一定要注意這兩個(gè)符號(hào),可能會(huì)導(dǎo)致json解析錯(cuò)誤.
//json數(shù)值 { "key" : 520, "key1" : 1314 } //json字符串 { "key" : "我愛你", "key1" : "一生一世" } //json數(shù)組 { "key" : [520, 1314], "key1" : [520, 3344] } //json對(duì)象數(shù)組 { "我" : [ {"key": "我愛你"}, {"key1": "一生一世"} ] } //json數(shù)組對(duì)象 { "我" : { [520,1314], ["我愛你", "一生一世"] } }
可以看出從汽車之家獲取的json字符串是json數(shù)組格式的,所以我們要用JSONArray進(jìn)行解析,然后再對(duì)json數(shù)組進(jìn)行遍歷,獲取每一個(gè)json對(duì)象,然后對(duì)json對(duì)象進(jìn)行數(shù)據(jù)的讀取.
//將json字符串解析成json數(shù)組的形式 JSONArray jsonArray = JSONArray.parseArray(result); //利用遍歷解析json數(shù)組,并在循環(huán)中解析每一個(gè)json對(duì)象 for (int i = 0; i < jsonArray.size(); i++) { //將json數(shù)組解析為每一個(gè)jsonObject對(duì)象 JSONObject object=jsonArray.getJSONObject(i); //實(shí)例化一個(gè)dao層或者domain層的對(duì)象 CarBrand Brand = new CarBrand(); //將json對(duì)象中的數(shù)據(jù)寫入實(shí)例化的對(duì)象中 //注意object讀取的字段要和json對(duì)象中的字段一樣,否則無法解析 Brand.setId(object.getInteger("id")); Brand.setName(object.getString("name")); Brand.setGroup(object.getString("letter")); }
將實(shí)例化對(duì)象的數(shù)據(jù)存入數(shù)據(jù)庫中
在springboot框架之中,mybatis-generator可以生成domain層的實(shí)體文件,xml文件,mapper文件和相應(yīng)的service文件,利用這個(gè)插件可以省去我們寫sql語句的時(shí)間,我們可以在service層直接調(diào)用相應(yīng)的方法.
//調(diào)用service層的add方法,直接將實(shí)例化對(duì)象寫入數(shù)據(jù)庫 CarBrandService.add(Brand);
完整代碼如下
package org.linlinjava.litemall.admin.service; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.linlinjava.litemall.db.dao.LitemallCarBrandMapper; import org.linlinjava.litemall.db.domain.LitemallCarBrand; import org.linlinjava.litemall.db.service.LitemallCarBrandService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.time.LocalDateTime; import java.util.List; import java.util.Map; @Service public class AdminCarBrandService { @Autowired CarBrandService carBrandService; public void httpRequest() { //使用httpclient獲取api數(shù)據(jù) CloseableHttpClient client = HttpClients.createDefault(); String apiPath = "https://www.autohome.com.cn/ashx/index/GetHomeFindCar.ashx"; HttpGet httpGet = new HttpGet(apiPath); try{ httpGet.addHeader("content-type","text/xml"); HttpResponse response = client.execute(httpGet); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { //對(duì)獲取的string數(shù)據(jù)進(jìn)行json解析 String result = EntityUtils.toString(response.getEntity()); JSONArray jsonArray = JSONArray.parseArray(result); for (int i = 0; i < jsonArray.size(); i++) { //將json對(duì)象中的數(shù)據(jù)寫入實(shí)例化對(duì)象中 CarBrand carBrand = new CarBrand(); JSONObject object=jsonArray.getJSONObject(i); carBrand.setId(object.getInteger("id")); carBrand.setName(object.getString("name")); carBrand.setGroup(object.getString("letter")); //將實(shí)例化對(duì)象存入數(shù)據(jù)庫 carBrandService.add(CarBrand); } } }catch (Exception e){ throw new RuntimeException(e); } } }
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
一文詳解SpringBoot中CommandLineRunner接口
Spring Boot的CommandLineRunner接口是一個(gè)函數(shù)式接口,用于在Spring Boot應(yīng)用程序啟動(dòng)后執(zhí)行一些初始化操作,它提供了一個(gè)run方法,該方法在應(yīng)用程序啟動(dòng)后被調(diào)用,本文給大家詳細(xì)介紹了SpringBoot中CommandLineRunner接口,需要的朋友可以參考下2023-10-10Mybatis實(shí)現(xiàn)分頁查詢的詳細(xì)流程
這篇文章主要給大家介紹了關(guān)于Mybatis實(shí)現(xiàn)分頁查詢的詳細(xì)流程,MyBatis是支持普通SQL查詢,存儲(chǔ)過程和高級(jí)映射的優(yōu)秀持久層框架,需要的朋友可以參考下2023-08-08java -jar后臺(tái)啟動(dòng)的四種方式小結(jié)
這篇文章主要介紹了java -jar后臺(tái)啟動(dòng)的四種方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-09-09Java編程實(shí)現(xiàn)游戲中的簡(jiǎn)單碰撞檢測(cè)功能示例
這篇文章主要介紹了Java編程中的簡(jiǎn)單碰撞檢測(cè)功能,涉及java針對(duì)坐標(biāo)點(diǎn)的相關(guān)數(shù)學(xué)運(yùn)算操作技巧,需要的朋友可以參考下2017-10-10java實(shí)現(xiàn)響應(yīng)重定向發(fā)送post請(qǐng)求操作示例
這篇文章主要介紹了java實(shí)現(xiàn)響應(yīng)重定向發(fā)送post請(qǐng)求操作,結(jié)合實(shí)例形式分析了java請(qǐng)求響應(yīng)、重定向及數(shù)據(jù)處理相關(guān)操作技巧,需要的朋友可以參考下2020-04-04Spring?boot?admin?服務(wù)監(jiān)控利器詳解
這篇文章主要介紹了Spring?boot?admin?服務(wù)監(jiān)控利器詳解,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-08-08SpringBoot 實(shí)戰(zhàn) 之 優(yōu)雅終止服務(wù)的方法
本篇文章主要介紹了SpringBoot 實(shí)戰(zhàn) 之 優(yōu)雅終止服務(wù)的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-05-05