Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass variable in JSON string in C#

Tags:

json

c#

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.

like image 564
murmansk Avatar asked Apr 17 '26 04:04

murmansk


2 Answers

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',
                    }"
like image 84
Rahul Avatar answered Apr 19 '26 17:04

Rahul


Here's an example the works for me:

string json = @"[ { 'email': '" + name + "' } ]";
like image 36
Jason Avatar answered Apr 19 '26 17:04

Jason



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!