Home  >  Article  >  Java  >  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?

WBOY
WBOYforward
2023-05-14 10:58:051641browse

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

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

    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!

    Statement:
    This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete