java使用fastJson读json格式的txt文件并且以json格式重新写入txt

处理的问题

json格式如下
java使用fastJson读json格式的txt文件并且以json格式重新写入txt_第1张图片
让第三层的数据设置精度为小数点后三位

一、导包

fastjson-1.2.2.jar
百度网盘:https://pan.baidu.com/s/17oYfgE7FY1Hk1WQhmVacvg
提取码:sda8
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.79</version>
</dependency>

二、代码

 public static void main(String[] args) throws Exception {

        Map<String, Object> map = parseFile("C:/Users/admin/Desktop/geojson.txt");
        updateData((JSONArray) map.get("coordinates"));
        outputFile("C:/Users/admin/Desktop/outputFile.txt",map.toString());

    }

    /* 写文件 */
    public static void outputFile(String path,String data) throws IOException {

        File file = new File(path);
        if(!file.exists()){
            file.createNewFile();
        }
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        fileOutputStream.write(data.getBytes());
        fileOutputStream.flush();
        fileOutputStream.close();

    }

    /* 读文件(json) */
    public static Map<String, Object> parseFile(String path) {
        try {
            File file = new File(path);
            if (file.isFile() && file.exists() && file.canRead()) {
                String encoding = "GBK";
                InputStreamReader in;
                in = new InputStreamReader(new FileInputStream(file), encoding);
                BufferedReader bufferedReader = new BufferedReader(in);
                String lineTxt = "";
                StringBuilder sb = new StringBuilder(lineTxt);
                while ((lineTxt = bufferedReader.readLine()) != null) {
                    if (!lineTxt.trim().equals("")) {
                        sb.append(lineTxt);
                    }
                }
                lineTxt = sb.toString();
                in.close();
                return JSON.parseObject(lineTxt);
            }else {
                System.out.println("找不到指定文件");
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /* 递归修改数据 */
    public static void updateData(JSONArray arr){
        int size = arr.size();
        Object o = null;
        for (int i=0 ; i<size ; i++){
            o = arr.get(i);
            if (o instanceof BigDecimal){
                arr.set(i,((BigDecimal) o).setScale(3,BigDecimal.ROUND_HALF_UP));
            }else {
                updateData((JSONArray)o);
            }
        }
    }

你可能感兴趣的:(java,json,开发语言,fastjson)