2

JSON String looks like

{
{"widget": {
    "debug": "on",
    "window": {
        "title": "Sample Konfabulator Widget",
        "name": "main_window",
        "width": 500,
        "height": 500,
        "stamp" : "randomtestcasenumberwithtimeID2",
        "case" : 1
    },
    "image": { 
        "src": "Images/Sun.png",
        "name": "sun1",
        "hOffset": 250,
        "vOffset": 250,
        "stamp" : "randomtestcasenumberwithtimeID3"
    
    },
}
}   

I want to replace all instances of "stamp" with something static such "stamp" : "Testing". How would I go about this? please note the value of "stamp" is random.

So after the search and replace both instance of stamp should have same value "Testing" Example

    {
{"widget": {
    "debug": "on",
    "window": {
        "title": "Sample Konfabulator Widget",
        "name": "main_window",
        "width": 500,
        "height": 500,
        "stamp" : "Testing",
        "case" : 1
    },
    "image": { 
        "src": "Images/Sun.png",
        "name": "sun1",
        "hOffset": 250,
        "vOffset": 250,
        "stamp" : "Testing"
    
    },
}
}   
Bounty Collector
  • 615
  • 7
  • 19

1 Answers1

1

You can try this:

String json = "<your-json-here>";
String newValue = "Testing";
String newJson = s.replaceAll("\"stamp\"\\s*:\\s*\"(.*)\"", String.format("\"stamp\" : \"%s\"", newValue));

or even something like this:

String s2 = s.replaceAll("(?<=\"stamp\")\\s*:\\s*\"(.*)(?=\")", ":\""+ newValue);
ETO
  • 6,970
  • 1
  • 20
  • 37