This is really out of scope for JSON libraries, since JSON format itself has no support or notion of variable substitution. Your best bet may be to use a JSON library (like Jackson) to get a tree representation (for Jackson that would be JsonNode), then traverse it, and use another library for handling textual substitution. There are many that can do that, from stringtemplate to others (perhaps MessageFormat that other answer refers to).
It may also be possible to revert the other, if your substitutions will never funny "funny characters" (quotes, linefeeds); if so, you could use string templating lib first, JSON parser next feeding processed text. But it is bit riskier, as usually there is eventually one case where you do end up trying to add a quote, say, and then parsing fails.
Answer from StaxMan on Stack OverflowThis is really out of scope for JSON libraries, since JSON format itself has no support or notion of variable substitution. Your best bet may be to use a JSON library (like Jackson) to get a tree representation (for Jackson that would be JsonNode), then traverse it, and use another library for handling textual substitution. There are many that can do that, from stringtemplate to others (perhaps MessageFormat that other answer refers to).
It may also be possible to revert the other, if your substitutions will never funny "funny characters" (quotes, linefeeds); if so, you could use string templating lib first, JSON parser next feeding processed text. But it is bit riskier, as usually there is eventually one case where you do end up trying to add a quote, say, and then parsing fails.
You can use a template engine such as Apache Velocity to preprocess the input stream, and then parse the result with a JSON parser. To make the process "on-the-fly", you can run Velocity in a separate thread, and let it write it's output to a PipedOutputStream.
If you are struggling to arrange the "'s the correct syntax would be
String jsonRequestString = "{\"access_code\" : \""+code+"\" , ";
Instead of formatting Json string manually, which takes alot of effort, consider using a library or util.
For ex (going to use Jackson library) :
Request re = new Request();
re.setCode(code);
...
ObjectMapper mapper = new ObjectMapper();
String jsonStr = mapper.writeValueAsString(re);
String yourVariable = "xyz";
String jsonRequestString = "{\"access_code\" : \"" + yourVariable + "\" , "
+ "\"merchant_reference\" : \"123\", \"language\" : \"en\",\"id\" : \"149018273\","
+ "\"merchant_identifier\" : \"gKc\", \"signature\" : \"570fd712af47995468550bec2655d9e23cdb451d\", "
+ "\"command\" : \"VOID\"}";
How to replace a value of a json file in java - Stack Overflow
How do I replace JSON variables in a JSON file with native JSON VIs.
java - Is there a general string substitution function similar to sl4fj? - Stack Overflow
java - How to including variables within strings? - Stack Overflow
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
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\"");
String.format
String str = String.format("Action %s occured on object %s.",
objectA.getAction(), objectB);
Or
String str = String.format("Action %s occured on object %s with outcome %s.",
new Object[]{objectA.getAction(), objectB, outcome});
You can also use numeric positions, for example to switch the parameters around:
String str = String.format("Action %2$s occured on object %1$s.",
objectA.getAction(), objectB);
You can use String.format or MessageFormat.format
E.g.,
MessageFormat.format("A sample value {1} with a sample string {0}",
new Object[] {"first", 1});
or simply
MessageFormat.format("A sample value {1} with a sample string {0}", "first", 1);
You can always use String.format(....). i.e.,
String string = String.format("A String %s %2d", aStringVar, anIntVar);
I'm not sure if that is attractive enough for you, but it can be quite handy. The syntax is the same as for printf and java.util.Formatter. I've used it much especially if I want to show tabular numeric data.
This is called string interpolation; it doesn't exist as such in Java.
One approach is to use String.format:
String string = String.format("A string %s", aVariable);
Another approach is to use a templating library such as Velocity or FreeMarker.
That link you provided is an excellent source since matching using patterns is the way to go. The basic idea here is first get the tokens using a matcher. After this you will have Operators and Operands
Then, do the replacement individually on each Operand.
Finally, put them back together using the Operators.
A somewhat tedious solution would be to scan for all occurences of A and B and note their indexes in the string, and then use StringBuilder.replace(int start, int end, String str) method. (in naive form this would not be very efficient though, approaching smth like square complexity, or more precisely "number of variables" * "number of possible replacements")
If you know all of your operators, you could do split on them (like on "+") and then replace individual "A" and "B" (you'd have to do trimming whitespace chars first of course) in an array or ArrayList.
So I'm assuming that you have a json object called jsonObject:
var url = "http://example.com/";
jsonObject.playlist[0] = url;
On the other hand, if you're talking about construction the json object, then you just put the variable into the right position:
var url = "http://example.com/";
var jsonObject = {playlist: [
url,
{
// our song
url: 'another URL goes here'
}
]
}
Note that there's no problem with url being used as a variable in our list, while also being used as a key in the object that comes right after it.
Remember that JSON stands for Javascript Object Notation. It's just a way to encode objects into a string so you can pass it about easily (eg: over HTTP). In your code, it should have already been parsed into an object, therefore you can modify it like any other object: it's nothing special.
var newURL = = document.getElementById('foo').href; // or whatever...
myObject.playlist[0] = newURL;