java读取json文件 新增到数据库表

3 篇文章 0 订阅
1 篇文章 0 订阅
   public void test2(){
      // 读取文件数据
      System.out.println("读取文件数据util");
      String pactFile = "D:/**.json";
      StringBuffer strbuffer = new StringBuffer();
      Long id = Long.valueOf(0);//字段1
      String  name = "";//字段2
      Long parentId = Long.valueOf(0);//字段3
      int lv = 0;//字段4
      File myFile = new File(pactFile);//"D:"+File.separatorChar+"**.json"
      //!myFile.exists()   判断文件是否存在  存在为!myFile.exists()即true
      if (!myFile.exists()) {
         System.err.println("Can't Find " + pactFile);
      }
      JSONArray jsonArray = null;
      try {
         //读取文件
         String input = FileUtils.readFileToString(myFile, "UTF-8");
         //将读取的文件转换为JSONObject 
         JSONObject jsonObject = JSONObject.fromObject(input);
         if (jsonObject != null) {
            //取出按钮权限的数据
            jsonArray = jsonObject.getJSONArray("list");
            System.out.println(jsonArray.size());
            //jsonArray.size()  json数据的大小(长度)
            //遍历jsonArray 转换格式,放入map集合中
            for(int i = 0; i < jsonArray.size(); i++){
               id = Long.valueOf(jsonArray.getJSONObject(i).get("id").toString());
               name = jsonArray.getJSONObject(i).get("name").toString();
               parentId = Long.valueOf(jsonArray.getJSONObject(i).get("parentId").toString());
               lv = 0;
               Map map =new HashMap();
               map.put("id",id);
               map.put("name",name);
               map.put("parentId",parentId);
               map.put("agencyId",lv);
               //新增到数据库
               sysRegionService.insert(map);
               //查看已执行次数
               System.out.println("已执行:" + i);
            }
         }
      } catch (Exception e) {
         e.printStackTrace();
         jsonArray = null;
      }
      System.out.println("已执行完毕");
   }
}
  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值