如何将字符串sUsername
插入myEmail
和sPassword
插入myPassword
?
sUsername
和sPassword
来自登录表单。
我刚刚学习JSON,我可以创建一个JSON变量并用sUsername
和sPassword
值填充它吗?
这是我的代码:
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());
}
}
答案 0 :(得分:1)
我认为你的json字符串无效,你应该正确格式化(参考这个link)
首先创建一个原始json,然后使用link转义json字符串
您可以使用以下代码附加字符串:
var json = "{ \"type\": \"login\", \"condition\": { \"0\": { \"key\": \"email\", \"value\": \"" + sUsername + "\" }, \"1\": { \"key\": \"password\", \"value\": \"" + password + "\" } }}";
=======修订=====
根据Jon Skeet的建议,使用JSON库为您的请求构建JSON对象。 以下是基于您的情况的示例代码。我使用NuGet的Newtonsoft.Json库。
1.创建一个班级:
public class LoginRequest
{
public string Type { get; set; }
public Dictionary<string,string> [] condition { get; set; }
}
2。使用Newtonsoft.Json库的序列化对象:
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);
请注意,使用JSON库非常简单且易于维护 而不是创建一个原始的JSON字符串。
希望这会对你有所帮助。
答案 1 :(得分:1)
如果你想构建你的JSON,你不需要Json.NET,你可以像这样使用anonymous type:
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);
答案 2 :(得分:0)
只需将变量添加到字符串
中string json = @"
{
""type"":""login"",
""condition"":{
""0"":{
""key"":""email"",
""value"":"+ sUsername +"
},
""1"":{
""key"":""password"",
""value"":"+ sPassword +"
}
}
}";