2016-12-17 57 views
0

我正在讀取我的xamarin.forms android應用程序中的webservice響應, 下面是包含狀態(0-錯誤,1-確定)消息的響應& info(info包含數據表數據行)在C#中讀取JSON響應Xamarin.Forms

{ 
"status": 1, 
"msg" : "OK", 
"info": { 
"UCode": "1", 
"UName": "Admin", 
"UPass": "pass" 
} 
} 

我能讀status & msg

如何將節點info的數據轉換爲User_Info類的Observable Collection?

這裏是我的代碼

  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

你確定你所需要的'info'被強制轉換爲'ObservableCollection'?因爲json使用的對象不是通常會轉換爲列表類型的數組。 – Anth12

回答

2

創建所需的模型類。您可以使用json2csharp。只需粘貼你的JSON字符串,然後按一下生成

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; } 
} 

然後你可以deserialise您的JSON字符串:

string jsonString = await resp.Content.ReadAsStringAsync(); 
Response response = JsonConvert.DeserializeObject<Response> (jsonString)); 

if (response.status == 1) { 
    Info info = response.info 
} 
+0

非常感謝。你救了我的一天 –

+0

不客氣。 – HeisenBerg