Xamarin JSON反序列化

时间:2018-07-26 03:19:12

标签: json xamarin xamarin.forms json-deserialization

我创建了一个HTTPWebRequest来检查用户名和密码是否正确。如果用户名和密码正确,它将返回带有用户的ContactID的JSON数组。我尝试反序列化JSON,但无法获取实际数据。我想获取联系人ID并将数据发送到下一页的变量。

用户名和密码正确时的JSON输出:

  

[{“ ContactID”:“ 1”}]

我的代码:

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Input;
using TBSMobileApplication.Data;
using TBSMobileApplication.View;
using Xamarin.Essentials;
using Xamarin.Forms;

namespace TBSMobileApplication.ViewModel
{
    public class LoginPageViewModel : INotifyPropertyChanged
    {
        void OnProperyChanged(string PropertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(PropertyName));
        }

        public string username;
        public string password;

        public string Username
        {
            get { return username; }
            set
            {
                username = value;
                OnProperyChanged(nameof(Username));
            }
        }

        public string Password
        {
            get { return password; }
            set
            {
                password = value;
                OnProperyChanged(nameof(Password));
            }
        }

        public ICommand LoginCommand { get; set; }

        public LoginPageViewModel()
        {
            LoginCommand = new Command(OnLogin);
        }

        public void OnLogin()
        {
            if (string.IsNullOrEmpty(Username) || string.IsNullOrEmpty(Password))
            {
                MessagingCenter.Send(this, "Login Alert", Username);
            }
            else
            {
                var current = Connectivity.NetworkAccess;

                if (current == NetworkAccess.Internet)
                {
                    var link = "http://192.168.1.25:7777/TBS/test.php?User=" + Username + "&Password=" + Password;
                    var request = HttpWebRequest.Create(string.Format(@link));
                    request.ContentType = "application/json";
                    request.Method = "GET";

                    using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                    {
                        if (response.StatusCode != HttpStatusCode.OK)
                        {
                            Console.Out.WriteLine("Error fetching data. Server returned status code: {0}", response.StatusCode);
                        }
                        else
                        {
                            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                            {
                                var content = reader.ReadToEnd();

                                if (content.Equals("[]") || string.IsNullOrWhiteSpace(content) || string.IsNullOrEmpty(content))
                                {
                                    MessagingCenter.Send(this, "Http", Username);
                                }
                                else
                                {
                                    var usr = JsonConvert.DeserializeObject(content);
                                    App.Current.MainPage.Navigation.PushAsync(new DatabaseSyncPage(), true);
                                }
                            }
                        }
                    }
                }
                else
                {
                    MessagingCenter.Send(this, "Not Connected", Username);
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }
}

2 个答案:

答案 0 :(得分:0)

JSON Response对象没有为输出结果寻找标准格式。无论使用哪种JSON反序列化,都应按照以下代码创建单独的类。

       public class RootObject
    {
        public string ContactID { get; set; }
    }

    Public Void ServiceRequest()
    {
      var content = reader.ReadToEnd();
     if(!String.IsNullOrEmpty(content)
    {
      var response = JsonConvert.DeserializeObject<RootObject>(content);
    }
}

我希望它会有用。

答案 1 :(得分:0)

按如下所示修改代码else

if (content.Equals("[]") || string.IsNullOrWhiteSpace(content) || string.IsNullOrEmpty(content))
{
    MessagingCenter.Send(this, "Http", Username);
}
else
{
    var response = JsonConvert.DeserializeObject<List<LoggedInUser>>(content);   
    var contactId=response[0].ContactID;
    //response have your ContactID value. Try to debug & see.
    App.Current.MainPage.Navigation.PushAsync(new DatabaseSyncPage(), true);
}

创建另一个公共课程来反序列化您的响应

public class LoggedInUser
{
    public string ContactID { get; set; }
}

如果结果中有1条以上的记录(如您在下面的评论中所要求的)  您可以使用循环获取它们

for (int i = 0; i < response.Count; i++)
{
   var item = response[i];
   var contactId = item.ContactId;
}

希望它能对您有所帮助。