user2826304
user2826304

Reputation: 117

How to replace a value of a json file in java

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.

Basically the json file contains the following string:

  "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.

Any help with this would be greatly appreciated.

Thanks.

Upvotes: 8

Views: 58445

Answers (3)

aleroot
aleroot

Reputation: 72696

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

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

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

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

Upvotes: 4

LC1NS4N3
LC1NS4N3

Reputation: 74

try this

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

Upvotes: 0

Rahul
Rahul

Reputation: 45090

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

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

Upvotes: 8

Related Questions