Henrik Henrik - 8 months ago 95
C# Question

Build hardcoded json string from input parameters

I´m trying to build a hardcoded json string with input parameters in method, but it seems that it doesn´t work. Am I doing wrong here?

public string Test(string name, string age)
string jsonData = @"{
""Name"":""' + name +'"",
""Age"":""' + age + '""

return jsonData;

Normally i would use Json.Net but i wonder if there is a way to do it like this. The reason is that i would only use it only in tests and dont want so spend some hours to create objects or anonymous objects to get this json.


Probably you think this (or @cactuaroid's answer) as correct one. But it is not. Use @LB's answer...

public string Test(string name, string age)
    return $@"{{""Name"":""{name}"" , ""Age"":""{age}""}}";

Just suppose, someone is calling it as var json = Test("abc\"def", "33"); ==> An invalid json...