如何使用Java更新JSON值

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

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);
        }
    }
}

特点:

  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 :

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 = &quot;{\n&quot; +
&quot;\&quot;msgType\&quot;: \&quot;NEW\&quot;,\n&quot; +
&quot;\&quot;code\&quot;: \&quot;205\&quot;,\n&quot; +
&quot;\&quot;plid\&quot;: \&quot;PLB52145\&quot;,\n&quot; +
&quot;}&quot;;
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&lt;&gt;(output));
}
@Override
public boolean onObjectMember(final CharSequence name) {
isPlid = &quot;plid&quot;.contentEquals(name);
return super.onObjectMember(name);
}
@Override
public boolean onStringValue(final CharSequence data) {
if (isPlid) {
if (&quot;PLB52145&quot;.contentEquals(data)) {
return super.onStringValue(&quot;PL809809809&quot;);
}
}
return super.onStringValue(data);
}
}
}

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 的文件中。此外,我没有理解你的变量赋值,所以我也已经进行了更新。请使用以下代码:

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(&quot;plid&quot;));
System.out.println(id);
jsonObject.put(&quot;plid&quot;,PL809809809);
System.out.println(jsonObject);
FileWriter writer = new FileWriter(filePath, false); //overwrites the content of file
writer.write(jsonObject.toString());
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:

确定