How to insert C# string into JSON string

Viewed 3459

How to insert string sUsername to myEmail and sPassword tomyPassword?

sUsername and sPassword are from the login form.

I'm just learning JSON, can I make a JSON variable and fill it with sUsername and sPassword values?

Here is my code:

public void login(string sUsername, string sPassword)
{
    var httpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("http://atsiri.online/api/v1.php");
    httpWebRequest.ContentType = "application/json";
    httpWebRequest.Method = "POST";

    using (var streamWriter = new System.IO.StreamWriter(httpWebRequest.GetRequestStream()))
    {
        string json = @"
        {
            ""type"":""login"",
            ""condition"":{
                ""0"":{
                    ""key"":""email"",
                    ""value"":""myEmail""
                },
                ""1"":{
                    ""key"":""password"",
                    ""value"":""myPassword""
                }
            }
        }";

        streamWriter.Write(json);
        streamWriter.Flush();
        streamWriter.Close();
    }

    var httpResponse = (System.Net.HttpWebResponse)httpWebRequest.GetResponse();
    using (var streamReader = new System.IO.StreamReader(httpResponse.GetResponseStream()))
    {
        var result = streamReader.ReadToEnd();
        Console.WriteLine(result.ToString());
    }
}
3 Answers

I think you are having an invalid json string, you should format it properly (refer to this link)

Make a raw json first then use that link to have escaped json string

You can append the string using this code:

var json = "{   \"type\": \"login\",    \"condition\": {        \"0\": {            \"key\": \"email\",         \"value\": \"" + sUsername + "\"        },      \"1\": {            \"key\": \"password\",          \"value\": \"" + password + "\"     }   }}";

enter image description here

=======UPDATED=====

As per Jon Skeet's advice to use JSON library to build your JSON object for your request. Here is a sample code that is based in your situation. I use Newtonsoft.Json library from NuGet.

1.Create a class:

public class LoginRequest
{
    public string Type { get; set; }
    public Dictionary<string,string> [] condition { get; set; }
}

2. Serialized object using Newtonsoft.Json library:

using Newtonsoft.Json;

var login = new LoginRequest
{
    Type = "login",
    condition = new Dictionary<string, string>[]

    {
        new Dictionary<string, string>()
        {
            {"key" , "email" },
            {"value", sUsername }
        },
        new Dictionary<string, string>()
        {
            {"key" , "password" },
            {"value", password }
        }
    }
};            
var jsonx = JsonConvert.SerializeObject(login);

enter image description here

Notice that it is very easy and more maintainable to use JSON library than to create a raw JSON string.

Hope this helps you.

You don't need Json.NET if you want to construct your JSON, you can use anonymous type like this:

var obj = new
{
    type = "login",
    condition = new Dictionary<string, object>()
    {
        { "0", new { key = "email", value = "myEmail" } },
        { "1", new { key = "password", value = "myPassword" } }
    }
};

string json = new JavaScriptSerializer().Serialize(obj);

Just add the variable into the string

string json = @"
        {
            ""type"":""login"",
            ""condition"":{
                ""0"":{
                    ""key"":""email"",
                    ""value"":"+ sUsername +"
                },
                ""1"":{
                    ""key"":""password"",
                    ""value"":"+ sPassword +"
                }
            }
        }";
Related