关于json格式,java主要有二种解析方式(还有一种谷歌的解析用的比较少):
1、net.sf.json.JSONObject
2、com.alibaba.fastjson.JSONObject
对于第一种和第二种有一个区别就是格式化json的时候,是否会改变对象的顺序。
下面是一段修改json文件的代码,采用第一种方式,为了保持原json顺序不变,大概思路就是将haisdb对象中的数据库连接(端口和地址):统一改为"host":"hais_db","port":3306,
json内容:
{
"haisdb": {
"readonly":false,
"client": "mysql",
"connection": {
"host": "155.155.1.177",
"user": "root",
"password": "123456",
"timezone": "0800",
"database": "hais"
},
"timezone": "+08:00",
"pool": {
"min": 1,
"max": 10
},
"acquireConnectionTimeout": 10800000
},
"redis": {
"host": "155.155.1.177",
"db": 0
}
}
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import net.sf.json.JSONObject;
import java.io.*;
public class UpdateJson {
public static void main(String[] args) {
String filePath = null;
File file = null;
if (args.length == 1){
filePath =args[0];
file = new File(filePath);
} else {
//filePath = "D:\\updateJson\\db.json";
//file = new File(filePath);
System.out.println("请输入要修改的db.json路径,退出码1");
System.exit(1);
}
if (!file.exists()){
System.out.println("该路径下没有db.json,程序异常退出,退出码1");
System.exit(1);
}
try {
//JSONObject jsonObject = JSON.parseObject(new FileInputStream(file), JSONObject.class);
String content = readFileByLines(filePath);
JSONObject jsonObject = JSONObject.fromObject(content);
System.out.println("程序开始读取db.json");
//获取haisdb对象
Object haisdb = jsonObject.get("haisdb");
//删除hais对象
jsonObject.remove("haisdb");
JSONObject haisdbJson = JSONObject.fromObject(haisdb);
//获取connection对象
String connection = haisdbJson.getString("connection");
//删除connection对象
haisdbJson.remove("connection");
JSONObject connectinJson = JSONObject.fromObject(connection);
connectinJson.put("host","hais_db");
connectinJson.put("port",3306);
haisdbJson.put("connection",connectinJson);
jsonObject.put("haisdb",haisdbJson);
Object redis = jsonObject.get("redis");
if (redis != null){
jsonObject.remove("redis");
JSONObject redisJson = JSONObject.fromObject(redis);
redisJson.put("host","hais_redis");
redisJson.put("port","6379");
jsonObject.put("redis",redisJson);
}
String pretty = JSON.toJSONString(jsonObject,
SerializerFeature.PrettyFormat,
SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteDateUseDateFormat);
BufferedWriter bw = new BufferedWriter(new FileWriter(filePath));
bw.write(pretty);
bw.flush();
bw.close();
System.out.println("程序正常退出,退出码0");
System.exit(0);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static String readFileByLines(String fileNmae){
BufferedReader reader = null;
String content = "";
String tempString = null;
try {
reader = new BufferedReader(new FileReader(new File(fileNmae)));
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 e) {
e.printStackTrace();
}
}
}
return content;
}
}