json - Xamarin JSON 反序列化
问题描述
我创建了一个 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;
}
}
解决方案
修改您的代码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;
}
希望对您有所帮助。
推荐阅读
- delphi - 如何在 Delphi 中执行类似于 C# Invoke() 的操作?
- java - 从 Java 字符串中删除空格
- jquery - 从同一个类中获取每个值,进行计算,然后用 jQuery 附加它
- node.js - Docker 错误 process_linux.go:319:从管道中获取最终孩子的 pid 导致“EOF”:未知
- variables - 如果留空,如何让 HTML 输入字段不发送字符串值 - 不发送任何内容
- php - Laravel - 未找到 - 在此服务器上找不到请求的资源/控件
- dpdk - DPDK 中实现的 cuckoo hash map 是否支持与 AVX512 的并行查找?
- c# - 刚体碰撞层
- javascript - querySelector 中的 Javascript Varialbe 返回 null
- json - 如何编组和解组 x509.Certificate 到/从 JSON?