Windows Phone 8.1 开发。 C#。 JSON
Windows Phone 8.1 development. C#. JSON
我目前正在开发 windows phone 8.1 应用程序,它需要使用 WEB API 从某些服务器登录。它需要多个参数作为 POST 数据,我需要接收一个 JSON 对象来处理多个 return 参数。请帮助我。
以下代码向 Web 服务器发送请求,我收到 HttpResponseMessage。我的问题是如何从此响应中提取数据。
Uri theUri = new Uri("myURI");
System.Net.Http.HttpClient aClient = new System.Net.Http.HttpClient();
aClient.DefaultRequestHeaders.Host = theUri.Host;
aClient.DefaultRequestHeaders.Add("Accept", "application/json");
DataContractJsonSerializer jsonSer = new DataContractJsonSerializer(typeof(TodoItem2)); //TodoItem2 is my class type of post data
MemoryStream ms = new MemoryStream();
jsonSer.WriteObject(ms, x);
ms.Position = 0;
StreamReader sr = new StreamReader(ms);
StringContent theContent = new StringContent(sr.ReadToEnd(), System.Text.Encoding.UTF8, "application/json");
HttpResponseMessage aResponse = await aClient.PostAsync(theUri, theContent);
if (aResponse.IsSuccessStatusCode)
{
tblMsg.Text = "Login Successful..";
}
else
{
tblMsg.Text = "Incorrect Credentials";
}
}
最好的方法:
string jsonMessage;
using (Stream responseStream = await aResponse .Content.ReadAsStreamAsync())
{
jsonMessage = new StreamReader(responseStream).ReadToEnd();
}
现在,如果您有收到的内容,您会在 json 消息变量中得到 json。
如果您想将其转换为对象,您必须创建一个 class,例如 class 命名的用户。您可以使用 Json.NET 库将 json 转换为 C# 对象:
User user = JsonConvert.DeserializeObject<User>(jsonMessage);
Json.NET 站点:http://www.newtonsoft.com/json
希望我帮到了你。
我目前正在开发 windows phone 8.1 应用程序,它需要使用 WEB API 从某些服务器登录。它需要多个参数作为 POST 数据,我需要接收一个 JSON 对象来处理多个 return 参数。请帮助我。
以下代码向 Web 服务器发送请求,我收到 HttpResponseMessage。我的问题是如何从此响应中提取数据。
Uri theUri = new Uri("myURI");
System.Net.Http.HttpClient aClient = new System.Net.Http.HttpClient();
aClient.DefaultRequestHeaders.Host = theUri.Host;
aClient.DefaultRequestHeaders.Add("Accept", "application/json");
DataContractJsonSerializer jsonSer = new DataContractJsonSerializer(typeof(TodoItem2)); //TodoItem2 is my class type of post data
MemoryStream ms = new MemoryStream();
jsonSer.WriteObject(ms, x);
ms.Position = 0;
StreamReader sr = new StreamReader(ms);
StringContent theContent = new StringContent(sr.ReadToEnd(), System.Text.Encoding.UTF8, "application/json");
HttpResponseMessage aResponse = await aClient.PostAsync(theUri, theContent);
if (aResponse.IsSuccessStatusCode)
{
tblMsg.Text = "Login Successful..";
}
else
{
tblMsg.Text = "Incorrect Credentials";
}
}
最好的方法:
string jsonMessage;
using (Stream responseStream = await aResponse .Content.ReadAsStreamAsync())
{
jsonMessage = new StreamReader(responseStream).ReadToEnd();
}
现在,如果您有收到的内容,您会在 json 消息变量中得到 json。
如果您想将其转换为对象,您必须创建一个 class,例如 class 命名的用户。您可以使用 Json.NET 库将 json 转换为 C# 对象:
User user = JsonConvert.DeserializeObject<User>(jsonMessage);
Json.NET 站点:http://www.newtonsoft.com/json
希望我帮到了你。