Json String - How to add variables to a string

I have a Json string as shown below

 String jsonRequestString = "{\"access_code\" : \"9bPbN3\" , "
                          + "\"merchant_reference\" : \"123\", \"language\" : \"en\",\"id\" : \"149018273\","
                          + "\"merchant_identifier\" : \"gKc\", \"signature\" : \"570fd712af47995468550bec2655d9e23cdb451d\", "
                          + "\"command\" : \"VOID\"}";

      

I have a String variable like

String code = "9bPbN3";

      

The question is, how can I connect the above line instead of hard-coding it below. that is, instead of 9bPbN3, I want to use the variable code there.

   String jsonRequestString = "{\"access_code\" : \"9bPbN3\" , "

      

Thank you very much in advance.

+3


source to share


4 answers


If you are trying to organize "

, the correct syntax would be

String jsonRequestString = "{\"access_code\" : \""+code+"\" , ";

      

Instead of manually formatting your Json string, which is a lot of effort, consider using a library or utility.



For ex (for using Jackson library):

Request re = new Request();
re.setCode(code);
...
ObjectMapper mapper = new ObjectMapper();
String jsonStr = mapper.writeValueAsString(re);

      

+5


source


String yourVariable = "xyz";
String jsonRequestString = "{\"access_code\" : \"" + yourVariable + "\" , "
                      + "\"merchant_reference\" : \"123\", \"language\" : \"en\",\"id\" : \"149018273\","
                      + "\"merchant_identifier\" : \"gKc\", \"signature\" : \"570fd712af47995468550bec2655d9e23cdb451d\", "
                      + "\"command\" : \"VOID\"}";

      



+3


source


The general advice is to avoid creating a json structure from vanilla strings. Use the json parser / writer library for these operations instead.

Checkout http://stleary.github.io/JSON-java/index.html / http://stleary.github.io/JSON-java/index.html .

Various other libraries and tutorials exist.

If you don't want to go in that direction, use the known value placeholder and replace it. So the full json will contain "access_code": "@@ ACCESS_CODE @@" and you will replace the placeholder with the real value. This way your json string will be a kind of string template.

+3


source


Another option is to use the method format

like this:

 String jsonRequestString = "{\"access_code\" : \"%s\" , "
                          + "\"merchant_reference\" : \"123\", \"language\" : \"en\",\"id\" : \"149018273\","
                          + "\"merchant_identifier\" : \"gKc\", \"signature\" : \"570fd712af47995468550bec2655d9e23cdb451d\", "
                          + "\"command\" : \"VOID\"}";
String code = "9bPbN3";
String result = String.format(jsonRequestString, code);

      

Notice the "% s" I put instead of space code

. When you call a method format

with code

as a parameter, it puts it where "% s" is.

+1


source







All Articles