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

查看:117
本文介绍了如何使用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天全站免登陆