Reputation: 131
I'm reading the response from a webservice in my xamarin.forms android app, below is the response which contains status (0-error, 1-OK) message & info (info contains datarows from datatable)
{
"status": 1,
"msg" : "OK",
"info": {
"UCode": "1",
"UName": "Admin",
"UPass": "pass"
}
}
I'm able to read status
& msg
.
How can I convert Data from node info into Observable Collection of class User_Info
?
Here is my code
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; }
List Classes
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; }
}
Upvotes: 0
Views: 3762
Reputation: 8001
Create the required model classes. You can use json2csharp. Just paste your JSON string there and click 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; }
}
Then your can deserialise your JSON string as:
string jsonString = await resp.Content.ReadAsStringAsync ();
Response response = JsonConvert.DeserializeObject<Response> (jsonString));
if (response.status == 1) {
Info info = response.info
}
Upvotes: 3