Xamarin JSON反序列化

Xamarin JSON反序列化,json,xamarin,xamarin.forms,json-deserialization,Json,Xamarin,Xamarin.forms,Json Deserialization,我创建了一个HTTPWebRequest来检查用户的用户名和密码是否正确。如果用户的用户名和密码正确,它将返回一个带有用户ContactID的JSON数组。我试图反序列化JSON,但未能获得实际数据。我想获取联系人id并将数据发送到下一页的变量 用户名和密码正确时JSON的输出: [{“联系人ID”:“1”}] 我的代码: using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Com

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

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

[{“联系人ID”:“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;
    }
}

JSON响应对象不是输出结果的标准格式。对于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);
    }
}
公共类根对象
{
公共字符串ContactID{get;set;}
}
Public Void ServiceRequest()
{
var content=reader.ReadToEnd();
如果(!String.IsNullOrEmpty(内容)
{
var response=JsonConvert.DeserializeObject(内容);
}
}

我希望它会有用。

修改您的代码
否则
块如下

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);
}
如果您在结果中有超过1条记录(如您在下面的评论中所问) 您可以使用循环获取它们

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

希望它能对您有所帮助。

我把这个放在哪里?在从服务器读取json数据后,只需使用反序列化,我具体在哪里粘贴代码?我把代码放在public void OnLogin()下{}出现错误。错误是什么?请粘贴完整的json字符串好吗?如果fix现在看到Arvindraja代码,现在的问题是将数据传递到其他视图显示我可以将值传递到下一页的变量吗?
response
在else块中设置ContactID值。尝试调试并查看响应内容。json数组名称是否相同是否必须使用公共字符串ContactID{get;set;}?出现错误“Newtonsoft.Json.Json序列化异常:无法将当前Json数组(例如[1,2,3])反序列化为类型“TBSMobileApplication.ViewModel.LoginPageViewModel+LoggedInUser”,因为该类型需要Json对象(例如,{“name”:“value”})是的,这是一个正确的异常,因为类中没有Json属性来反序列化这个对象{“name”:“value”}。根据异常,Json是以数组格式出现的。所以您应该像这样使用-var response=JsonConvert.DeserializeObject(content);
for (int i = 0; i < response.Count; i++)
{
   var item = response[i];
   var contactId = item.ContactId;
}