我正在读取我的xamarin.forms android应用程序中的webservice的响应, 以下是包含状态(0-error,1-OK)消息的响应& info(info包含来自datatable的数据行)
{
"status": 1,
"msg" : "OK",
"info": {
"UCode": "1",
"UName": "Admin",
"UPass": "pass"
}
}
我能够阅读status
& msg
。
如何将数据从节点信息转换为类User_Info
的可观察集合?
这是我的代码
try
{
using (var client = new HttpClient())
{
var url = GSVar.hostname + GSVar.user_check;
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string,string>("uname",T1.Text),
new KeyValuePair<string, string>("upass",T2.Text)
});
var resp = await client.PostAsync(new Uri(url), content);
//var resp = await client.GetAsync(new Uri(url));
if (resp.IsSuccessStatusCode)
{
var result = JsonConvert.DeserializeObject<Json_Respnce>(resp.Content.ReadAsStringAsync().Result);
if (result.status == 0)
General.GSErr(result.msg);
else
{
//User_Info user_info = JsonConvert.DeserializeObject<User_Info>(result.UserInfo);
//await DisplayAlert("OK", result.UserInfo.ToString(), "OK");
}
}
else
General.GSErr("Nothing retrieved from server.");
}
}
catch { throw; }
列出类
class Json_Respnce
{
[JsonProperty(PropertyName ="status")]
public int status { get; set; }
[JsonProperty(PropertyName = "msg")]
public string msg { get; set; }
//[JsonProperty(PropertyName = "info")]
//public string UserInfo { get; set; }
}
class User_Info
{
[JsonProperty(PropertyName = "UCode")]
public string UCode { get; set; }
[JsonProperty(PropertyName = "UName")]
public string UName { get; set; }
[JsonProperty(PropertyName = "UPass")]
public string UPass { get; set; }
}
答案 0 :(得分:3)
创建所需的模型类。您可以使用json2csharp。只需将JSON字符串粘贴到那里,然后单击Generate
public class Info
{
public string UCode { get; set; }
public string UName { get; set; }
public string UPass { get; set; }
}
public class Response
{
public int status { get; set; }
public string msg { get; set; }
public Info info { get; set; }
}
然后你可以将你的JSON字符串反序列化为:
string jsonString = await resp.Content.ReadAsStringAsync ();
Response response = JsonConvert.DeserializeObject<Response> (jsonString));
if (response.status == 1) {
Info info = response.info
}