Reputation: 331
I am facing trouble to replace some value inside a string.
{"key1":"value1","key2":"value2","key3":"value3","key4":"djdhsja","BizProcessNm":"value5",.........}
I have to replace the value of key4 to "something". As shown below
{"key1":"value1","key2":"value2","key3":"value3","key4":"something","BizProcessNm":"value5",.........}
The problem is I don't know the exact value inside the value of key4. In this case, "djdhsja" is the value. It will be random.
I thought of getting the position of key4 in the string and then based on the string position, replace the content after first " till it ends with "something". But this may be a little complicated as i have to do this for so many strings inside a for loop(The loop was written by someone else, I am just modifying it).
Is there any regex kind of find and replace like sed in linux.
edit: The position of key4 is random
Upvotes: 0
Views: 1747
Reputation: 1011
You can convert your String into JSon Object and then convert that json into Map and perform your tasks,
Map map;
map = (Map) JSONObject.toBean(jsonObj, Map.class);
Iterator it = map.entrySet().iterator();
Here jsonObj
is json object which is get cretaed from your String value.
and on Conditional check for key, update the value of the particular key.
Upvotes: 1
Reputation: 1507
Assuming that there is no whitespace between key, colon and value and also no quotation mark inside the current value of key4
you can use the following line of code to replace the value:
s.replaceFirst("(?<=\\\"key4\\\":\\\")(.*?)(?=\\\")", "new value");
The regex is using positive look-behind and look-ahead so that only the text inside the quotation marks of the value is replaced.
While this may be applicable for a one-time action I'd rather suggest using a JSON-parser as suggested in the comments and Marcell's answer.
Upvotes: 1
Reputation: 163
If I'm not mistaken, you have JSON-like key-value pairs. In that case I would convert the json into a java object. There are some libraries written for that (ex. https://github.com/FasterXML/jackson). Than you can simply get and set the fields of that object.
If it is a map, or something similar, you can still get the value of "key4" by the key "key4".
And finally, if you have something totally else, like a string with that content, you can use something like:
yourString.split(",")[3].split(":")[1];
Upvotes: 1