Table of Contents
Java calls the interface to obtain json data and save it to the database
in ServiceImpl to call the interface and parse Json characters Serialize and store in the database
Get the json string through the api interface
Use JSONArray and JSONObject to parse json strings
Store the data of the instantiated object in the database
Home Java javaTutorial How does Java call the interface to obtain json data and save it to the database after parsing it?

How does Java call the interface to obtain json data and save it to the database after parsing it?

May 14, 2023 am 10:58 AM
java json database

    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
    Copy after login

    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();//调用业务层方法
        }
    Copy after login

    3. Add method

        /**
         * @Title: 查询
         * @Description: 查询车辆的记录
         * @Author: 半度纳
         * @Date: 2022/9/27 17:33
         * @return
         */
        public boolean selectBlacklist();//返回值类型没要求
    Copy after login

    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;
            }
        }
    Copy after login

    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();
    Copy after login

    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()获取状态码
    Copy after login

    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],
                      ["我爱你", "一生一世"]
        }
    }
    Copy after login

    How does Java call the interface to obtain json data and save it to the database after parsing it?

    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"));
    }
    Copy after login

    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);
    Copy after login

    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);
            }
     
        }
    }
    Copy after login

    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!

    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    Hello Kitty Island Adventure: How To Get Giant Seeds
    1 months ago By 尊渡假赌尊渡假赌尊渡假赌
    Two Point Museum: All Exhibits And Where To Find Them
    1 months ago By 尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    Square Root in Java Square Root in Java Aug 30, 2024 pm 04:26 PM

    Guide to Square Root in Java. Here we discuss how Square Root works in Java with example and its code implementation respectively.

    Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

    Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

    Random Number Generator in Java Random Number Generator in Java Aug 30, 2024 pm 04:27 PM

    Guide to Random Number Generator in Java. Here we discuss Functions in Java with examples and two different Generators with ther examples.

    Armstrong Number in Java Armstrong Number in Java Aug 30, 2024 pm 04:26 PM

    Guide to the Armstrong Number in Java. Here we discuss an introduction to Armstrong's number in java along with some of the code.

    Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

    Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

    Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

    Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

    Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

    In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

    Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

    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

    See all articles