Java读写Json文件

java读写JSon文件有以下:

(1)将JSon文件通过普通文本文件的方式进行读取,并且存放在一个字符串中。

(2)创建一个JSon对象,并将字符串初始化到JSon对象中,这里需要引入一个JSon的包Json-org.jar引入包的具体做法如下:

  • 下载json-org.jar的包放在本地目录中
  • 读写json文件所在的项目中buildpath--》configureBuidpath--》add external jar然后将json-org.jar包导入到项目中

(3)通过创建的JSon对象完成对数据的操作和处理

(4)将操作完成的JSon对象转换成字符串

(5)将字符串存放在指定的Json文件中

下面的代码操作的是src/json目录下的test.json文件,实现的功能是添加“nameID”字段并且删除“ISO”字段,并存放在src/json目录下newFile.json新的文件中,文件的内容如下:

{
"type": "FeatureCollection",  
    "features": [{  
        "type": "Feature",  
        "properties": {  
            "name": "Yuen Long",  
            "ID_0": 102,  
            "ID_1": 18,  
            "ISO": "HKG"  
        },  
        "geometry": {  
            "type": "Polygon",  
            "coordinates": [[[114.084511, 22.519991], [114.075668, 22.517466], [114.078194, 22.516203], [114.079460, 22.516623], [114.082825, 22.519150], [114.084511, 22.519991]]]  
        }  
    }]
}

代码如下:

public class test {
    public static void main(String[] args) {
        ArrayList list = new ArrayList(); 
        list.add("admin");
        //读取json文件
        try {
            BufferedReader br = new BufferedReader(new FileReader("src/json/test.json"));
            BufferedWriter bw=new BufferedWriter(new FileWriter("src/json/newFile.json"));
            String str=null;
            String data="";
            while((str=br.readLine())!=null) {
                data=data+str+"\n";
            }
            JSONObject dataJson = new JSONObject(data);
            JSONArray features=dataJson.getJSONArray("features");
            for (int i = 0; i < features.length(); i++) {  
                JSONObject info = features.getJSONObject(i);// 获取features数组的第i个json对象  
                JSONObject properties = info.getJSONObject("properties");// 找到properties的json对象  
                String name = properties.getString("name");// 读取properties对象里的name字段值  
                System.out.println(name);  
                properties.put("NAMEID", list.get(i));// 添加NAMEID字段  
                // properties.append("name", list.get(i));  
                System.out.println(properties.getString("NAMEID"));  
                properties.remove("ISO");// 删除ISO字段 
                String ws=dataJson.toString();
                System.out.println(ws);
                bw.write(ws);  
                // bw.newLine();  
                bw.flush();  
                br.close();  
                bw.close();
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }// 读取原始json文件 
 catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}    
    }

}

你可能感兴趣的:(Java读写Json文件)