Java解析JSON文件

这篇文章主要讲讲 通过java去解析不同地方的json文件

通常我们需要解析本地的json文件或者服务器上的json文件。我们用来解析json格式的jar包有很多,jackson,fastjson,gson都行。但本人喜欢用fastjson。所以本篇都是以fastjson来解析json文件。

1.解析本地json文件

随便把一个json文件存储在本地的一个文件夹下,然后通过文件流将json文件内容读取出来。

然后转换成String,最后转json对象,然后再解析,获取自己想要的数据。

首先我们这个json文件的格式是:

{
    "type": "FeatureCollection",
    "features": [
        {
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": [
                    121.4672,
                    31.11606
                ]
            },
            "properties": {
                "id": "16N5877",
                "q": 1
            }
        },
        {
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": [
                    121.531212,
                    31.3701954
                ]
            }
        }
    ]
}

下面我们用到的是字符流:

	//把一个文件中的内容读取成一个String字符串
    public static String getStr(File jsonFile){
        String jsonStr = "";
        try {
            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;
        }
    }

然后解析这个json

@Test
    public void shuiLing(){
        String json = "E:\\gis\\data\\pd20192021-07-08.json";
        File jsonFile = new File(json);
        //通过上面那个方法获取json文件的内容
        String jsonData = CommonUtil.getJsonStr(jsonFile);
        //转json对象
        JSONObject parse = (JSONObject)JSONObject.parse(jsonData);
        //获取主要数据
        JSONArray features = parse.getJSONArray("features");
        //挨个遍历 
        for (Object feature : features) {
            JSONObject featureObject =(JSONObject)feature;
            JSONObject properties = featureObject.getJSONObject("properties");
            JSONObject geometry = featureObject.getJSONObject("geometry");
            JSONArray coordinates = geometry.getJSONArray("coordinates");
//            System.out.println(coordinates);
            //通过创建对应的实体类去存储对应数据然后存库
            GisDetails gisDetails = new GisDetails();
            gisDetails.setCreateTime(new Date());
            String date = jsonFile.getName();
	 gisDetails.setDatetime(date.substring(date.indexOf("2021"),date.indexOf('.')));
            gisDetails.setId(properties.getString("id"));
            gisDetails.setQ(new BigDecimal(properties.getString("q")));
            gisDetails.setLat(new BigDecimal(coordinates.getString(1))); //维度
            gisDetails.setLon(new BigDecimal(coordinates.getString(0))); // 经度
//            System.out.println(properties);
            //如果数据量大不建议这样入库 直接拼接sql 然后插入一次
            int i = gisService.insertGisDetails(gisDetails);
            if (i>=0){
                log.info("==>成功"+gisDetails);
            }else{
                log.info("==》失败"+gisDetails);
            }
        }
    }

2.访问服务器上的json文件并解析到数据库中

使用这种方式就有一个坑需要注意了,通过url拉下来的json文件不能直接转json对象,因为有很多的斜杠和多余的引号需要处理。

然后还多了一步需要对url进行连接,连接成功才能读取json内容。

所以这里使用的java原生的URL去访问资源。然后我们通过tomcat去模拟。当然其他的url都可以读取,只要浏览器里能打开,并且是json格式。

@Test
public void shuiLing2(){
    String json = "http://localhost:8110/static/test2021-07-08.json";
    // 通过URL去访问服务器上的资源
    URL url = null;
    try {
        url = new URL(json);
        URLConnection urlCon = url.openConnection();
        urlCon.connect();         //获取连接
        InputStream is = urlCon.getInputStream();
        BufferedReader buffer = new BufferedReader(new InputStreamReader(is));
        StringBuffer bs = new StringBuffer();
        String l = null;
        while((l=buffer.readLine())!=null){
            bs.append(l).append("/n");
        }
        //去斜杠和引号
        String s = JSON.toJSONString(bs);
        s = s.replaceAll("\\\\","");
        //多余的换行符
        s = s.replace("/n","");
        //对第一个引号和最后一个引号处理
        s = s.substring(1,s.length()-1);
        JSONObject parse = (JSONObject)JSONObject.parse(s);
        JSONArray features = parse.getJSONArray("features");
        for (Object feature : features) {
            JSONObject featureObject =(JSONObject)feature;
            JSONObject properties = featureObject.getJSONObject("properties");
            JSONObject geometry = featureObject.getJSONObject("geometry");
            JSONArray coordinates = geometry.getJSONArray("coordinates");
            GisDetails gisDetails = new GisDetails();
            gisDetails.setCreateTime(new Date());
            gisDetails.setDatetime(json.substring(json.indexOf("2021"),json.indexOf('.')));
            gisDetails.setId(properties.getString("id"));
            gisDetails.setQ(new BigDecimal(properties.getString("q")));
            gisDetails.setLat(new BigDecimal(coordinates.getString(1))); //维度
            gisDetails.setLon(new BigDecimal(coordinates.getString(0))); // 经度
            int i = gisService.insertGisDetails(gisDetails);
            if (i>=0){
                log.info("==>成功"+gisDetails);
            }else{
                log.info("==》失败"+gisDetails);
            }
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

然后如果对你有帮助记得点赞喔!

  • 39
    点赞
  • 170
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值