


How does Java call the interface to obtain json data and save it to the database after parsing it?
Java calls the interface to obtain json data and save it to the database
1. Configure your own defined interface URL in the yml file
//自己定义的JSON接口URL blacklist_data_url: 接口URL
2 .Add request method and path in Controller
/** * @Title: 查询 * @Description: 查询车辆的记录 * @Author: 半度纳 * @Date: 2022/9/27 17:33 */ @GetMapping("/Blacklist") public void selectBlacklist(){ boolean a = imBuBlacklistService.selectBlacklist();//调用业务层方法 }
3. Add method
/** * @Title: 查询 * @Description: 查询车辆的记录 * @Author: 半度纳 * @Date: 2022/9/27 17:33 * @return */ public boolean selectBlacklist();//返回值类型没要求
4 in Service. Implement method
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接口数据(在输出测试时sendGet方法可能会自动输出,具体需看底层代码) String list= HttpUtils.sendGet(blacklist_data_url); JSONObject j = JSON.parseObject(list);//将获取的JSON数据存储到变量中 if(j.getBoolean("success")){//获取success判断是否为空 JSONObject jsonData = j.getJSONObject("body");//解析JSON的body JSONArray jsonArray = jsonData.getJSONArray("data");//解析JSON的data数据 JSONObject row = null;//定义一个空变量 ImBuBlacklist buBlacklist=new ImBuBlacklist();//new一个实体类用来接收数据 for (int y = 0; y < jsonArray.size(); ++y) {//循环将JSON数据存储到数据库中 buBlacklist = new ImBuBlacklist();//new一个实体类存储数据 row = jsonArray.getJSONObject(y);//获取数组中的数据 //设置获取到的JSON号牌号码到实体类的相同字段中 buBlacklist.setPlateNumber(row.getString("mechanicalNumber")); //设置获取到的JSON车辆类型到实体类的相同字段中 buBlacklist.setVehicleType(row.getString("machType")); //设置获取到的JSON检查日期到实体类的相同字段中 buBlacklist.setExamineDate(row.getDate("createDate")); //设置获取到的JSON检查地点到实体类的相同字段中 buBlacklist.setExamineAddress(row.getString("machineAddr")); //设置获取到的JSON违规行为到实体类的相同字段中 buBlacklist.setIllegalBehavior(row.getString("joinTheBlacklistReason")); //设置获取到的JSON黑名单类型到实体类的相同字段中 buBlacklist.setBlacklistType(row.getInteger("violations")); //通过mapper的新增方法,把实体类中的JSON数据存到数据库中 imBuBlacklistMapper.insertImBuBlacklist(buBlacklist); } return true;//自己定义的返回值(没有用) }else{ return false; } }
in ServiceImpl to call the interface and parse Json characters Serialize and store in the database
Get the json string through the api interface
Get the interface data through the get(httpGet) request. There are basically six steps to use HttpClient:
-
Create an HttpClient instance
Create an instance of a certain connection method
-
Call the execute method of the HttpClient instance to execute the request method
Read response
Release the connection, regardless of whether the execution method is successful or not
//创建httpClient实例 CloseableHttpClient client = HttpClients.createDefault(); //汽车之家api接口 String apiPath = "https://www.autohome.com.cn/ashx/index/GetHomeFindCar.ashx"; //创建get方法请求实例 HttpGet httpGet = new HttpGet(apiPath); //添加表头,text/xml表示XML格式 httpGet.addHeader("content-type","text/xml"); //调用HttpClient实例执行GET实例,返回response HttpResponse response = client.execute(httpGet); //解析response,这个过程主要取决于获取的json格式,是一个对象还是一个数组,放到后面详解 String result = EntityUtils.toString(response.getEntity()); //释放连接 response.close(); client.close();
We can respond to the response Judge the status (state) to verify whether the data is obtained. The status values of the page request are: 200 request successful, 303 redirect, 400 request error, 401 unauthorized, 403 access forbidden, 404 file not found, 500 server error .
(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()方法返回保存请求状态的StatusLine对象,getStatusCode()获取状态码
Use JSONArray and JSONObject to parse json strings
Before parsing the json string, we must first determine the format of the json string. Different parsing methods must be used for different formats. Here are some common json String format
For example: numerical value, string, array, object array or array object. The key point is the use of curly brackets and square brackets. Be sure to pay attention to these two symbols, which may cause json parsing errors.
//json数值 { "key" : 520, "key1" : 1314 } //json字符串 { "key" : "我爱你", "key1" : "一生一世" } //json数组 { "key" : [520, 1314], "key1" : [520, 3344] } //json对象数组 { "我" : [ {"key": "我爱你"}, {"key1": "一生一世"} ] } //json数组对象 { "我" : { [520,1314], ["我爱你", "一生一世"] } }
It can be seen that the json string obtained from Autohome is in json array format, so we need to use JSONArray to parse, and then traverse the json array. Get each json object, and then read the data from the json object.
//将json字符串解析成json数组的形式 JSONArray jsonArray = JSONArray.parseArray(result); //利用遍历解析json数组,并在循环中解析每一个json对象 for (int i = 0; i < jsonArray.size(); i++) { //将json数组解析为每一个jsonObject对象 JSONObject object=jsonArray.getJSONObject(i); //实例化一个dao层或者domain层的对象 CarBrand Brand = new CarBrand(); //将json对象中的数据写入实例化的对象中 //注意object读取的字段要和json对象中的字段一样,否则无法解析 Brand.setId(object.getInteger("id")); Brand.setName(object.getString("name")); Brand.setGroup(object.getString("letter")); }
Store the data of the instantiated object in the database
In the springboot framework, mybatis-generator can generate Domain layer entity files, xml files, mapper files and corresponding service files. Using this plug-in can save us the time of writing sql statements. We can directly call the corresponding methods in the service layer.
//调用service层的add方法,直接将实例化对象写入数据库 CarBrandService.add(Brand);
Complete code As follows
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数据 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) { //对获取的string数据进行json解析 String result = EntityUtils.toString(response.getEntity()); JSONArray jsonArray = JSONArray.parseArray(result); for (int i = 0; i < jsonArray.size(); i++) { //将json对象中的数据写入实例化对象中 CarBrand carBrand = new CarBrand(); JSONObject object=jsonArray.getJSONObject(i); carBrand.setId(object.getInteger("id")); carBrand.setName(object.getString("name")); carBrand.setGroup(object.getString("letter")); //将实例化对象存入数据库 carBrandService.add(CarBrand); } } }catch (Exception e){ throw new RuntimeException(e); } } }
The above is the detailed content of How does Java call the interface to obtain json data and save it to the database after parsing it?. For more information, please follow other related articles on the PHP Chinese website!

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

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

Dreamweaver Mac version
Visual web development tools

Dreamweaver CS6
Visual web development tools