对json文件的读取修改

1.目的

读取某json文件, 对其中的key或者value进行修改

2.步骤

1.读取json文件内容   存放到jsonString中

2.将jsonString转为jsonObject

3.对jsonObject进行处理, 实现修改

4.将jsonObject转为jsonString(字符串)

5.写入初始josn文件

 

3.代码

 

1.读取json

 public static String readJsonFile(String path){
        String laststrJson = "";
        BufferedReader reader;
        try {
            reader = new BufferedReader(new FileReader(new File(path)));
            String tempString = null;
            int line = 1;
            // 一次读入一行,直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                laststrJson = laststrJson + tempString;
                line++;
            }
            reader.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return laststrJson;
    }

 

2.jsonString 转jsonObject

String jsonString = JsonUtils.readJsonFile(filePath);

JSONObject jsonObject=JSONObject.fromObject(jsonString);

 

3.jsonObject处理

String dataUrl=jsonObject.getString("dataUrl");
jsonObject.put("dataUrl",newDataUrl);

 

4.jsonObject转jsonString

jsonString= JSON.toJSONString(jsonObject);
	

 

5.写入源文件

 public static void writeJsonFile(String newJsonString, String path){
        try {
            FileWriter fw = new FileWriter(path);
            PrintWriter out = new PrintWriter(fw);
            out.write(newJsonString);
            out.println();
            fw.close();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值