如何使用 Java 更新 JSON 值 [英] How to Update JSON value using Java

查看:27
本文介绍了如何使用 Java 更新 JSON 值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 json,我想更新该 json 的每个值,但有时只有一个值

I have below json, i want to update each and every value of that json but sometimes only one value

{ 
"msgType": "NEW",
"code": "205",
"plid": "PLB52145",
}

我已经尝试使用以下代码进行更新

I've already tried to update using below code

FileReader reader = new FileReader(filePath);

JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);

System.out.println(jsonObject);


long id =Long.valueOf((String) idNewObj.get("plid"));
System.out.println(plid);


idNewObj.put("plid",PL809809809);

System.out.println(jsonObject);

推荐答案

您需要将更新后的 JSON 写入读取 JSON 的文件中.另外,我不明白你的变量赋值,所以我也更新了.使用以下代码:

You need to write the updated JSON into the file from where JSON was read. Also, I did not understand your variable assignment so I have updated that as well. Use below code:

FileReader reader = new FileReader(filePath);

JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);

System.out.println(jsonObject);


long id =Long.valueOf((String) idNewObj.get("plid"));
System.out.println(id);


jsonObject.put("plid",PL809809809);

System.out.println(jsonObject);
FileWriter writer = new FileWriter(filePath, false); //overwrites the content of file
writer.write(jsonObject.toString());
writer.close();

这篇关于如何使用 Java 更新 JSON 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆