Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json String - How to add variables in the string

I have a Json string like 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 as

String code = "9bPbN3";

Question, how do I plugin the above string instead of hardcoding it at the below place. i.e. instead of 9bPbN3, I want to use the variable code there.

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

Many Thanks in advance.

like image 706
user2967948 Avatar asked Mar 22 '17 12:03

user2967948


1 Answers

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);
like image 84
Suresh Atta Avatar answered Oct 21 '22 05:10

Suresh Atta