如何使用Java更新JSON值

huangapple go评论116阅读模式
英文:

How to Update JSON value using Java

问题

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

  1. {
  2. "msgType": "NEW",
  3. "code": "205",
  4. "plid": "PLB52145"
  5. }

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

  1. FileReader reader = new FileReader(filePath);
  2. JSONParser jsonParser = new JSONParser();
  3. JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
  4. System.out.println(jsonObject);
  5. long id = Long.valueOf((String) idNewObj.get("plid"));
  6. System.out.println(plid);
  7. idNewObj.put("plid", PL809809809);
  8. System.out.println(jsonObject);
英文:

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

  1. {
  2. "msgType": "NEW",
  3. "code": "205",
  4. "plid": "PLB52145",
  5. }

I've already tried to update using below code

  1. FileReader reader = new FileReader(filePath);
  2. JSONParser jsonParser = new JSONParser();
  3. JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
  4. System.out.println(jsonObject);
  5. long id =Long.valueOf((String) idNewObj.get("plid"));
  6. System.out.println(plid);
  7. idNewObj.put("plid",PL809809809);
  8. System.out.println(jsonObject);

答案1

得分: 0

为了对JSON文件进行转换/过滤,建议使用流/事件导向的解析和生成,而不是使用任何对象映射。以下是一个示例,它使用简单且轻量级的JSON解析器 https://github.com/anatolygudkov/green-jelly

  1. import org.green.jelly.AppendableWriter;
  2. import org.green.jelly.JsonEventPump;
  3. import org.green.jelly.JsonParser;
  4. import java.io.StringWriter;
  5. import java.io.Writer;
  6. public class UpdateMyJson {
  7. private static final String jsonToUpdate = "{\"msgType\": \"NEW\",\"code\": \"205\",\"plid\": \"PLB52145\"}";
  8. public static void main(String[] args) {
  9. final StringWriter result = new StringWriter();
  10. final JsonParser parser = new JsonParser();
  11. parser.setListener(new MyJsonUpdater(result));
  12. parser.parse(jsonToUpdate);
  13. parser.eoj();
  14. System.out.println(result);
  15. }
  16. static class MyJsonUpdater extends JsonEventPump {
  17. private boolean isPlid;
  18. MyJsonUpdater(final Writer output) {
  19. super(new AppendableWriter<>(output));
  20. }
  21. @Override
  22. public boolean onObjectMember(final CharSequence name) {
  23. isPlid = "plid".contentEquals(name);
  24. return super.onObjectMember(name);
  25. }
  26. @Override
  27. public boolean onStringValue(final CharSequence data) {
  28. if (isPlid) {
  29. if ("PLB52145".contentEquals(data)) {
  30. return super.onStringValue("PL809809809");
  31. }
  32. }
  33. return super.onStringValue(data);
  34. }
  35. }
  36. }

特点:

  1. 文件/数据不需要完全加载到内存中,可以处理大量的数据,无需担心问题。
  2. 对于大文件,它的处理速度更快。
  3. 使用这种模式可以轻松实现任何自定义类型/转换规则。

标准的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 :

  1. import org.green.jelly.AppendableWriter;
  2. import org.green.jelly.JsonEventPump;
  3. import org.green.jelly.JsonParser;
  4. import java.io.StringWriter;
  5. import java.io.Writer;
  6. public class UpdateMyJson {
  7. private static final String jsonToUpdate = &quot;{\n&quot; +
  8. &quot;\&quot;msgType\&quot;: \&quot;NEW\&quot;,\n&quot; +
  9. &quot;\&quot;code\&quot;: \&quot;205\&quot;,\n&quot; +
  10. &quot;\&quot;plid\&quot;: \&quot;PLB52145\&quot;,\n&quot; +
  11. &quot;}&quot;;
  12. public static void main(String[] args) {
  13. final StringWriter result = new StringWriter();
  14. final JsonParser parser = new JsonParser();
  15. parser.setListener(new MyJsonUpdater(result));
  16. parser.parse(jsonToUpdate); // if you read a file with a buffer,
  17. // call parse() several times part by part in a loop until EOF
  18. parser.eoj(); // and then call .eoj()
  19. System.out.println(result);
  20. }
  21. static class MyJsonUpdater extends JsonEventPump {
  22. private boolean isPlid;
  23. MyJsonUpdater(final Writer output) {
  24. super(new AppendableWriter&lt;&gt;(output));
  25. }
  26. @Override
  27. public boolean onObjectMember(final CharSequence name) {
  28. isPlid = &quot;plid&quot;.contentEquals(name);
  29. return super.onObjectMember(name);
  30. }
  31. @Override
  32. public boolean onStringValue(final CharSequence data) {
  33. if (isPlid) {
  34. if (&quot;PLB52145&quot;.contentEquals(data)) {
  35. return super.onStringValue(&quot;PL809809809&quot;);
  36. }
  37. }
  38. return super.onStringValue(data);
  39. }
  40. }
  41. }

Props:

  1. the file/data doesn't require to be loaded entirely into memory, you can process megs/gigs with no problems
  2. it works much more faster, especially for large files
  3. 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 的文件中。此外,我没有理解你的变量赋值,所以我也已经进行了更新。请使用以下代码:

  1. FileReader reader = new FileReader(filePath);
  2. JSONParser jsonParser = new JSONParser();
  3. JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
  4. System.out.println(jsonObject);
  5. long id = Long.valueOf((String) idNewObj.get("plid"));
  6. System.out.println(id);
  7. jsonObject.put("plid", 809809809);
  8. System.out.println(jsonObject);
  9. FileWriter writer = new FileWriter(filePath, false); // 覆盖文件的内容
  10. writer.write(jsonObject.toString());
  11. 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:

  1. FileReader reader = new FileReader(filePath);
  2. JSONParser jsonParser = new JSONParser();
  3. JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
  4. System.out.println(jsonObject);
  5. long id =Long.valueOf((String) idNewObj.get(&quot;plid&quot;));
  6. System.out.println(id);
  7. jsonObject.put(&quot;plid&quot;,PL809809809);
  8. System.out.println(jsonObject);
  9. FileWriter writer = new FileWriter(filePath, false); //overwrites the content of file
  10. writer.write(jsonObject.toString());
  11. writer.close();

huangapple
  • 本文由 发表于 2020年10月19日 14:58:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/64422516.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定