【问题标题】:Xamarin JSON DeserializeXamarin JSON 反序列化
【发布时间】:2019-01-02 22:59:33
【问题描述】:

我创建了一个 HTTPWebRequest 来检查用户的用户名和密码是否正确。如果用户的用户名和密码正确,它将返回一个 JSON 数组,其中包含用户的 ContactID。我试图反序列化 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;
    }
}

【问题讨论】:

    标签: json xamarin xamarin.forms json-deserialization


    【解决方案1】:

    修改您的代码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;
    }
    

    希望对你有帮助。

    【讨论】:

    • 如何将变量值传递到下一页?
    • response 在 else 块中有 ContactID 值。尝试调试并查看响应的结果。
    • Json Array Name 是否与 public string ContactID { get;放; } 还是不一定?
    • 出现错误“Newtonsoft.Json.JsonSerializationException: 无法将当前 JSON 数组(例如 [1,2,3])反序列化为 'TBSMobileApplication.ViewModel.LoginPageViewModel+LoggedInUser' 类型,因为该类型需要正确反序列化的 JSON 对象(例如 {"name":"value"})。"
    • 是的,这是正确的例外,因为类中没有用于反序列化此对象的 Json 属性{"name":"value"}。并且根据异常 Json 以数组格式出现。所以你应该像这样使用 - var response = JsonConvert.DeserializeObject>(content);
    【解决方案2】:

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

    希望对你有用。

    【讨论】:

    • 我把这个放在哪里?
    • 从服务器读取json数据后,只需使用反序列化
    • 具体在哪里粘贴代码?我把代码放在 public void OnLogin() {} 下面有一个错误。
    • 有什么错误可以粘贴完整的 json 字符串吗?
    • 如果现在修复看到 Arvindraja 代码,现在的问题是将数据传递给其他视图
    猜你喜欢
    • 1970-01-01
    • 2021-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-09
    • 2020-11-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多