Click here to Skip to main content
15,891,184 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I want to concatenate values with in a json string in asp.net with c#. I am getting Invalid JSON Primitive while seriailizing.

What I have tried:

<pre>


            string jsonstr2 = @"{'bankId':" + bankid + ",'password': " + password + ",'userName': " + userName + "}";


HandShakeRequest resultT2 = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<HandShakeRequest>(jsonstr2);
Posted
Updated 13-Jun-18 22:08pm
Comments
F-ES Sitecore 14-Jun-18 4:29am    
There's nothing wrong with the code per se, it's likely the issue is with special characters that are in the variables you are using, such as apostrophes, quotes etc. If that's the case you'll need to encode them.
Richard Deeming 14-Jun-18 11:46am    
Why are you creating a JSON string in C# if you're just going to immediately parse it into an object?

Just create the HandShakeRequest object directly.
HandShakeRequest resultT2 = new HandShakeRequest
{
    BankId = bankId,
    UserName = userName,
    Password = password,
};

1 solution

you can try below

var obj={};
obj.bankId=bankid;
obj.password=password ;
obj.userName=userName ;

string jsonstr2=JSON.stringify(obj);


and in C#

HandShakeRequest resultT2 =JsonConvert.DeserializeObject<HandShakeRequest>(jsonstr2)



you need to use Newtonsoft.Json for this

This link will be helpful[^]
 
Share this answer
 
v2
Comments
ranio 14-Jun-18 6:56am    
I am able to pass values concatenated fine for the first one. But second one getting invalid json delimiter




First one fine
string jsonstr = @"{""bankId"": 049, ""password"": ""P049563445634674574325323674we5476956789057905694565745764256456"", ""userName"":""6919301721649254400252100878956720265267481307739303873300957305"",""timestamp"":""10:00:00""}";

Output of first one which is fine:

{
"bankId": 1,
"password": "foo",
"signature": "",
"userName": "bar"
}

HandShakeRequest resultT = new JavaScriptSerializer().Deserialize<handshakerequest>(jsonstr);



Second one getting invalid json delimiter
string jsonstr2 = @"{'bankId':" + bankid + ",'password': " + password + ",'userName': " + userName + "}";

Output:
{
'bankId': 1,
'password': "foo",
'signature': "",
'userName': "bar"
}

Output of the second one which is getting issue as invalid json delimiter
string jsonstr2 = @"{'bankId':" + bankid + ",'password': " + password + ",'userName': " + userName + "}";

HandShakeRequest resultT = new JavaScriptSerializer().Deserialize<handshakerequest>(jsonstr);

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900