如何在java中替换json文件的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19704996/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 19:32:46  来源:igfitidea点击:

How to replace a value of a json file in java

java

提问by user2826304

Hello members of stackoverflow,

你好,stackoverflow 的成员,

I need some help with replacing a line in a json file. I have attempted using the same method i use to replace a line in a text file with no success.

我需要一些帮助来替换 json 文件中的一行。我曾尝试使用与替换文本文件中的一行相同的方法,但没有成功。

Basically the json file contains the following string:

基本上 json 文件包含以下字符串:

  "id": "TEXT",

And i want to replace the "TEXT" with "HELLO"

我想用“你好”替换“文本”

How would i do this, also i have the 'json_simple' library imported if that is of any use for this.

我将如何执行此操作,如果对此有任何用处,我还导入了“json_simple”库。

Any help with this would be greatly appreciated.

对此的任何帮助将不胜感激。

Thanks.

谢谢。

采纳答案by aleroot

Without using a JSON parser as someone suggested, you can do it simply with a regex :

不使用某人建议的 JSON 解析器,您只需使用正则表达式即可:

str = str.replaceAll("(\s*?\"id\"\s*?:\s*?)\"TEXT\",", "\"HELLO\"");

If the "TEXT" string is an unique placeholder for your replacement, you could simply use String replacemethod, in this way :

如果“TEXT”字符串是您替换的唯一占位符,您可以简单地使用字符串替换方法,如下所示:

str.replace("\"TEXT\"", "\"HELLO\"");

回答by SudoRahul

You cannot replace a value as such. Therefore, you need to remove it from the json and add it back.

您不能替换这样的值。因此,您需要将其从 json 中删除并重新添加。

JSONObject js = new JSONObject(); // Your jsonobject here, this is just a sample
js.remove("id"); // Since you want to replace the value associated with id, remove it
js.put("id", "HELLO"); // add the new value for id

回答by LC1NS4N3

try this

尝试这个

>     "id": {
>         "type": "String",
>         "value": "TEXT" ...
> 
> JSONObject modifiedjson=new JSONObject();
> modifiedjson.put("type",childobject.get("type"));
> modifiedjson.put("id","HELLO");