首页 > 编程语言 > Java读取json数据并存入数据库的操作代码
2022
05-27

Java读取json数据并存入数据库的操作代码

Java读取json数据并存入数据库

1. pom依赖

<dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.47</version>
 </dependency>

2.students.json文件

{
  "students": [
    {
      "stuId": 1,
      "stuName": "meilanfang",
      "stuAge": 93
    },
    {
      "stuId": 2,
      "stuName": "zhangguorong",
      "stuAge": 92
    },
    {
      "stuId": 3,
      "stuName": "huangjiaju",
      "stuAge": 91
    }
  ]
}

3.读取json文件方式一

//读取json文件
    public static String readJsonFile(String fileName) {
        String jsonStr = "";
        try {
            File jsonFile = new File(fileName);
            FileReader fileReader = new FileReader(jsonFile);
            Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            jsonStr = sb.toString();
            return jsonStr;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


    public static void main(String[] args) {
        String path = JsonTest.class.getClassLoader().getResource("students.json").getPath();
        String s = readJsonFile(path);
        JSONObject jobj = JSON.parseObject(s);
        JSONArray student = jobj.getJSONArray("students");//构建JSONArray数组
        for (int i = 0 ; i < student.size();i++){
            JSONObject key = (JSONObject)student.get(i);
            int stuId= (Integer)key.get("stuId");
            String stuName= (String)key.get("stuName");
            int stuAge= (Integer)key.get("stuAge");
            #TODO 数据库操作
            System.out.println(stuId);
            System.out.println(stuName);
            System.out.println(stuAge);
        }
    }

4.java 通过url下载图片保存到本地

//java 通过url下载图片保存到本地
   public static void download(String urlString, int i) throws Exception {
       // 构造URL
       URL url = new URL(urlString);
       // 打开连接
       URLConnection con = url.openConnection();
       // 输入流
       InputStream is = con.getInputStream();
       // 1K的数据缓冲
       byte[] bs = new byte[1024];
       // 读取到的数据长度
       int len;
       // 输出的文件流
       String filename = "D:\\图片下载/" + i + ".jpg";  //下载路径及下载图片名称
       File file = new File(filename);
       FileOutputStream os = new FileOutputStream(file, true);
       // 开始读取
       while ((len = is.read(bs)) != -1) {
           os.write(bs, 0, len);
       }
       System.out.println(i);
       // 完毕,关闭所有链接
       os.close();
       is.close();
   }

5.获取聚合数据车辆服务

 @Test
    public void doGetTestOne() {
        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 创建Get请求
        CloseableHttpResponse response = null;

        try {
            // 响应模型

            for(int f=200;f<=300;f++){
                HttpGet httpGet = new HttpGet("http://apis.juhe.cn/cxdq/series?brandid=" + f + "&levelid=&key=XXXXXXXXXXXX");
            // 由客户端执行(发送)Get请求
            response = httpClient.execute(httpGet);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            System.out.println("响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
                System.out.println("响应内容长度为:" + responseEntity.getContentLength());
//                System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
                JSONObject object = JSONObject.parseObject(EntityUtils.toString(responseEntity));
                JSONArray arr = object.getJSONArray("result");
                for (int i = 0; i < arr.size(); i++) {
                    JSONObject j = arr.getJSONObject(i);
                    CarBrandDetail vo = new CarBrandDetail();
                    vo.setId(j.getInteger("id"));
                    vo.setName(j.getString("name"));
                    vo.setBrandId(j.getInteger("brandid"));
                    vo.setLevelId(j.getInteger("levelid"));
                    vo.setLevelName(j.getString("levelname"));
                    vo.setSname(j.getString("sname"));
                    vo.setCreateTime(new Date());
                    int insert = carBrandMapper.insert(vo);
                    if (insert > 0) {
                        System.out.println("true");
                    }
                }
            }
        } }catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

ps:java读取json文件把数据存入数据库中

//读取json文件
    public static String readJsonFile(String fileName) {
        String jsonStr = "";
        try {
            File jsonFile = new File(fileName);
            FileReader fileReader = new FileReader(jsonFile);
            Reader reader = new InputStreamReader(new FileInputStream(jsonFile), "utf-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            jsonStr = sb.toString();
            return jsonStr;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
 public Result<?> test() {
        String s = readJsonFile("D:\\marks.json");
        JSONObject jobj = JSON.parseObject(s);
        JSONArray jsonArray = jobj.getJSONObject("data").getJSONObject("map_set").getJSONObject("map_code_set")
                .getJSONObject("mapSet").getJSONArray("markers");//构建JSONArray数组
//        JSONArray movies = jobj.getJSONObject("data").getJSONObject("map_set").
// getJSONObject("map_code_set").getJSONObject("mapSet").getJSONArray("polyline");//构建JSONArray数组
 
        for (int i = 0; i < jsonArray.size(); i++) {
            LongMarchStation longMarchStation = new LongMarchStation();
            JSONObject key = (JSONObject) jsonArray.get(i);
            JSONObject jsonObject = ((JSONObject) jsonArray.get(i)).getJSONObject("callout");
            String id = key.get("id") + "";
            String latitude = key.get("latitude") + "";
            String longitude = key.get("longitude") + "";
            Integer min = (Integer) key.get("min");
            Integer max = (Integer) key.get("max");
            String iconPath = (String) key.get("iconPath");
            String name = (String) jsonObject.get("content");
            longMarchStation.setId(id);
            longMarchStation.setLatitude(latitude);
            longMarchStation.setLongitude(longitude);
            longMarchStation.setMax(max);
            longMarchStation.setMin(min);
            longMarchStation.setName(name);
            longMarchStation.setIconPath(iconPath);
            longMarchStationService.save(longMarchStation);
        }
 
        return Result.ok("添加成功!");
    }

到此这篇关于Java读取json数据并存入数据库的文章就介绍到这了,更多相关JAVA son存入数据库内容请搜索自学编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持自学编程网!

编程技巧