1.介绍
开发过程中经常会遇到json数据的处理,而单独对json数据进行增删改并不方便,尤其是Geojson文件的处理,通过对网络资料的整理总结,下面介绍Java语言方法对json数据进行读取、添加、删除与修改操作。
2.说明
Java语言操作json对象,需引入json数据操作库(org.json.jar)文件,可通过网络搜索寻找,另外本文附件代码中已包含,在Eclipse或其它编译工具中直接引入即可。
pom 依赖:注意json-lib的属性有时需要加classifier属性,有时可以不用添加。
net.sf.json-lib
json-lib
2.4
jdk15 //此处要加上jdk版本号
本文通过一个json文件(json.config)为例进行介绍,将key为confKey 的参数替换所其他值。json2.config为修改后的新文件。
3.json样例
[
{
"business":"default",
"confKey":"b",
"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]]]
}
}]
},
{
"business":"default",
"confKey":"b",
"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]]]
}
}]
}
]
4、代码
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import java.io.*;
public class JsonConvert {
/**
* @param args
*/
public static void main(String[] args) {
// 读取原始json文件并进行操作和输出
try {
String s1 = readFileByLines("C:\\Users\\admin\\Desktop\\json.config"); // 读取配置文件
String ws = null;
BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\Users\\admin\\Desktop\\json2.config")); // 输出配置文件
JSONArray dataJson = JSONArray.fromObject(s1);
for (int i = 0; i < dataJson.size(); i++) {
JSONObject properties = (JSONObject) dataJson.get(i);
properties.put("confKey","repalceParams"); // 需要替换的参数
ws = dataJson.toString();
System.out.println(ws);
}
bw.write(ws);
bw.flush();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static String readFileByLines(String fileName) {
FileInputStream file = null;
BufferedReader reader = null;
InputStreamReader inputFileReader = null;
String content = "";
String tempString = null;
try {
file = new FileInputStream(fileName);
inputFileReader = new InputStreamReader(file, "utf-8");
reader = new BufferedReader(inputFileReader);
// 一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
content += tempString;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
return content;
}
}