


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!

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.
