java读取json文件,并修改json数据写出

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

添加json数据

String path = "src/main/webapp/json/bottomFgs.json";
String jsonStr = JsonUtils.readJsonFile(path);  

JSONArray jsonArray = JSONArray.fromObject(jsonStr);

JSONObject nbnewjson = new JSONObject();
nbnewjson.accumulate("have", "0");

JSONObject newjson = new JSONObject();
newjson.accumulate("id", newModelid);
newjson.accumulate("state", "closed");
newjson.accumulate("pId", "md001");
newjson.accumulate("text", addname);
newjson.accumulate("attributes", nbnewjson);

jsonArray.add(newjson);
//将json转换为json字符串
String newJsonString = jsonArray.toString();

JsonUtils.writeJsonFile(newJsonString, path); 

删除json数据

String path = "src/main/webapp/json/bottomFgs.json";
String jsonStr = JsonUtils.readJsonFile(path);  

JSONArray jsonArray = JSONArray.fromObject(jsonStr);
int size = jsonArray.size();

for(int  i = 0; i < size; i++){
    JSONObject jsonObject = jsonArray.getJSONObject(i);
    if(model.getModelid().equals(jsonObject.getString("id"))){
        jsonArray.remove(jsonObject);
    }
}

//将json转换为json字符串
String newJsonString = jsonArray.toString();
JsonUtils.writeJsonFile(newJsonString, path);

JsonUtils类

package com.zcl.oa.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class JsonUtils {

    /**
     * 读取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;
    }

    /**
     * 写出json文件
     */
    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();
        }
    }

}
  • 3
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 9
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值