英文:
How to Update JSON value using Java
问题
我有以下 JSON,我想更新该 JSON 的每个值,但有时只更新一个值。
{
"msgType": "NEW",
"code": "205",
"plid": "PLB52145"
}
我已经尝试使用以下代码进行更新:
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);
英文:
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);
答案1
得分: 0
为了对JSON文件进行转换/过滤,建议使用流/事件导向的解析和生成,而不是使用任何对象映射。以下是一个示例,它使用简单且轻量级的JSON解析器 https://github.com/anatolygudkov/green-jelly :
import org.green.jelly.AppendableWriter;
import org.green.jelly.JsonEventPump;
import org.green.jelly.JsonParser;
import java.io.StringWriter;
import java.io.Writer;
public class UpdateMyJson {
private static final String jsonToUpdate = "{\"msgType\": \"NEW\",\"code\": \"205\",\"plid\": \"PLB52145\"}";
public static void main(String[] args) {
final StringWriter result = new StringWriter();
final JsonParser parser = new JsonParser();
parser.setListener(new MyJsonUpdater(result));
parser.parse(jsonToUpdate);
parser.eoj();
System.out.println(result);
}
static class MyJsonUpdater extends JsonEventPump {
private boolean isPlid;
MyJsonUpdater(final Writer output) {
super(new AppendableWriter<>(output));
}
@Override
public boolean onObjectMember(final CharSequence name) {
isPlid = "plid".contentEquals(name);
return super.onObjectMember(name);
}
@Override
public boolean onStringValue(final CharSequence data) {
if (isPlid) {
if ("PLB52145".contentEquals(data)) {
return super.onStringValue("PL809809809");
}
}
return super.onStringValue(data);
}
}
}
特点:
- 文件/数据不需要完全加载到内存中,可以处理大量的数据,无需担心问题。
- 对于大文件,它的处理速度更快。
- 使用这种模式可以轻松实现任何自定义类型/转换规则。
标准的Gson和Jackson库也提供了用于以流式方式处理JSON的令牌解析器。
更新:使用了JsonEventPump。
英文:
To make transformation/filtering of JSON files, I'd suggest to use stream/event-oriented parsing and generating rather than any object mapping. Just an example, which uses simple and lightweight JSON parser https://github.com/anatolygudkov/green-jelly :
import org.green.jelly.AppendableWriter;
import org.green.jelly.JsonEventPump;
import org.green.jelly.JsonParser;
import java.io.StringWriter;
import java.io.Writer;
public class UpdateMyJson {
private static final String jsonToUpdate = "{\n" +
"\"msgType\": \"NEW\",\n" +
"\"code\": \"205\",\n" +
"\"plid\": \"PLB52145\",\n" +
"}";
public static void main(String[] args) {
final StringWriter result = new StringWriter();
final JsonParser parser = new JsonParser();
parser.setListener(new MyJsonUpdater(result));
parser.parse(jsonToUpdate); // if you read a file with a buffer,
// call parse() several times part by part in a loop until EOF
parser.eoj(); // and then call .eoj()
System.out.println(result);
}
static class MyJsonUpdater extends JsonEventPump {
private boolean isPlid;
MyJsonUpdater(final Writer output) {
super(new AppendableWriter<>(output));
}
@Override
public boolean onObjectMember(final CharSequence name) {
isPlid = "plid".contentEquals(name);
return super.onObjectMember(name);
}
@Override
public boolean onStringValue(final CharSequence data) {
if (isPlid) {
if ("PLB52145".contentEquals(data)) {
return super.onStringValue("PL809809809");
}
}
return super.onStringValue(data);
}
}
}
Props:
- the file/data doesn't require to be loaded entirely into memory, you can process megs/gigs with no problems
- it works much more faster, especially for large files
- it's easy to implement any custom type/rule of transformation with this pattern
Both of standard Gson and Jackson libs also provide tokenizers to work with JSON in streaming manner.
UPDATED: JsonEventPump used
答案2
得分: -1
你需要将更新后的 JSON 写入从中读取 JSON 的文件中。此外,我没有理解你的变量赋值,所以我也已经进行了更新。请使用以下代码:
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", 809809809);
System.out.println(jsonObject);
FileWriter writer = new FileWriter(filePath, false); // 覆盖文件的内容
writer.write(jsonObject.toString());
writer.close();
英文:
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();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论