Java读取并修改保存JSON文件
Posted CodeLogs
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java读取并修改保存JSON文件相关的知识,希望对你有一定的参考价值。
文章目录
JSON文件存放在项目的resources资源目录下,内容如下:
test.json
"core": 123,
"channel":"ok",
"parameter":[
"aaa","bbb","ccc"
],
"content": [
"reader":"xiaoming",
"writer":"lisi"
]
POM依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
读取JSON文件
private String readJsonFile()
String jsonStr = "";
try
InputStream in = getClass().getClassLoader().getResourceAsStream("test.json");
Reader reader = new InputStreamReader(in,"utf-8");
int ch = 0;
StringBuffer sb = new StringBuffer();
while ((ch = reader.read()) != -1)
sb.append((char) ch);
reader.close();
jsonStr = sb.toString();
return jsonStr;
catch (IOException e)
e.printStackTrace();
return null;
解析JSON
JSONObject jobj = JSON.parseObject(readJsonFile());
System.out.println("=======节点元素=======");
System.out.println(jobj.get("core"));
System.out.println(jobj.get("channel"));
System.out.println("=======列表元素=======");
System.out.println(jobj.getJSONArray("parameter").get(1));
JSONObject contentObj = (JSONObject) jobj.getJSONArray("content").get(0);
System.out.println(contentObj.get("writer"));
//修改元素方法与操作map类似,通过put(key,value)完成
jobj.put("core","333")
输出结果:
=节点元素=
123
ok
=列表元素=
bbb
lisi
生成新JSON文件
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
private void writeJsonFile(JSONObject jobj)
String content = JSON.toJSONString(jobj, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteDateUseDateFormat);
try
File file = new File(System.getProperty("user.dir")+ File.separator+ "New.json");
if (file.exists())
file.delete();
file.createNewFile();
// 写入文件
Writer write = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8);
write.write(content);
write.flush();
write.close();
catch (Exception e)
e.printStackTrace();
以上是关于Java读取并修改保存JSON文件的主要内容,如果未能解决你的问题,请参考以下文章
八Delphi10.3读取JSON文件,并修改JSON数组一条内容后保存到文件