3

How do I pass my variable in JSON string as shown below?

string name = "john";
string json = @"{  
                    'EmployeeName': name, 
                    'EmployeeID': '123',
                }

When I try the above I get an error.

0

3 Answers 3

4

Well you can concate the variable like

   string json =@"{  
                          'EmployeeName':" + name +", 
                          'EmployeeID': '123',
                    }"

You can as well consider using string.Format() for this purpose and in C# 6 you can use variable interpolation syntax like

   string json =$"{  
                          'EmployeeName': {name} , 
                          'EmployeeID': '123',
                    }"
Sign up to request clarification or add additional context in comments.

Comments

2

Here's an example the works for me:

string json = @"[ { 'email': '" + name + "' } ]";

Comments

0

It looks like you're passing the 'name' as a part of your string. You need to concatenate this like below, then it should work

string json =@"{  
                      'EmployeeName': " + name +", 
                      'EmployeeID': '123',
                }"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.