0

Below is a string which I want to dynamically pass to Json:

String username = 'IntegrationUser' 

Below is the json format wherein I want to pass username. But this does not work.

String payload = '{"UserID": '+ username + '}'; 

I even tried below line of code but didnt work

String payload = '{"UserID":'+username +'}'; 

How to pass this dynamic value ?

4 Answers 4

5

I always recommend using the serialize method to generate correct JSON:

String payload = JSON.serialize( new Map<String, Object> { 'UserID' => username }); 

This will emit the correct JSON, even if your username were to contain special characters, etc.

1

Your payload isn't formatted correctly. You need to wrap your dynamic string in double-quotes. These quotes won't need to be escaped, but it might be worth escaping your string to avoid any " causing the string to end prematurely.

String payload = '{"UserID":"'+username +'"}'; 
-1

req.setBody('{"accountid":"0015g000004mi4BAAQ","name":"'+myname+'","website":"'+web+'"}');

works perfectly

1
  • 2
    Welcome to SFSE! Please take the tour and read How to Answer. Code dumps (where you provide code with no explanation) are of limited value to the community and are discouraged. This also doesn't seem to line up very well with the question that was being asked. The person asking the question stated that building the JSON in this manner wasn't working. Also,req.setBody() is not mentioned anywhere in the question. It's important to read and understand the question before answering, to explain your solution, and to make it relevent to the question being asked. Commented Jul 16, 2021 at 13:43
-2
userObject uo = new userObject(); uo.userId = 'someId'; // here's your JSON object string jsonString = JSON.serialize(uo); 

// class code

public class userObject{ public string UserId{get;set;} } 
2
  • Not sure why the downvotes, this is essentially the same as sfdcfox mentioned in the other answer. I'm just serializing a class object instead of a map. Commented Mar 1, 2018 at 1:20
  • Hi Jason, I just saw that you were in the queue for "low quality', probably because of the downvotes. Answers like what you've written are generally discouraged here. The problem with this answer is that it has just a few lines of code and no explanation of how or why it works. While it is technically correct, and essentially the same as my answer (it's an alternative version of the same thing, which is totally acceptable), without an explanation, it simply won't be received favorably. Try to remember this in the future. Don't want you to be discouraged (we need all the help we can get!). Commented Mar 1, 2018 at 2:17

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.