我有一個我無法解決的問題。我需要反序列化一個Json。對于沒有父母的Json,它可以正常作業,但對于父母“專案”它不起作用,我的課程如下:
public partial class Root<T>
{
[JsonProperty("items")]
public T Items { get; set; }
}
public partial class Item
{
[JsonProperty("nombre")]
public string Nombre { get; set; }
[JsonProperty("ape")]
public string Ape { get; set; }
[JsonProperty("email")]
public string Email { get; set; }
[JsonProperty("pass")]
public string Pass { get; set; }
[JsonProperty("foto")]
public string Foto { get; set; }
}
回傳此型別 json 的 api:
{"items":
[{
"id":"9",
"nombre":"Fran",
"ape":"",
"email":"[email protected]",
"pass":"example2022",
"foto":"namePhoto.jpeg"
}]
}
我的方法總是回傳一個空值,我找不到解決方案,有誰知道可能發生了什么:
public async Task EmailApiGet(string pass)
{
var request = new HttpRequestMessage();
request.RequestUri = new System.Uri("https://app.adress.com/movil/rest/index.php?email=" Email.Value);
request.Method = HttpMethod.Get;
request.Headers.Add("Accept", "application/json");
var client = new HttpClient();
HttpResponseMessage response = await client.SendAsync(request);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
string json = await response.Content.ReadAsStringAsync();
Root<Item> name = JsonConvert.DeserializeObject<Root<Item>>(json); //Test
Console.WriteLine(name.Items.Nombre);
}
}
讀取Jsonresponse.Content.ReadAsStringAsync();確定,但在下一行中,反序列化回傳我NULL。
uj5u.com熱心網友回復:
感謝 GSerg 同事修復。我已將班級更改為:
public partial class Root
{
[JsonProperty("items")]
public Item[] Items { get; set; }
}
public partial class Item
{
[JsonProperty("id")]
[JsonConverter(typeof(ParseStringConverter))]
public long Id { get; set; }
[JsonProperty("nombre")]
public string Nombre { get; set; }
[JsonProperty("ape")]
public string Ape { get; set; }
[JsonProperty("email")]
public string Email { get; set; }
[JsonProperty("pass")]
public string Pass { get; set; }
[JsonProperty("foto")]
public string Foto { get; set; }
}
和我的方法:
public async Task EmailApiGet(string pass)
{
var request = new HttpRequestMessage();
request.RequestUri = new System.Uri("https://app.example.com/example/rest/index.php?email=" Email.Value);
request.Method = HttpMethod.Get;
request.Headers.Add("Accept", "application/json");
var client = new HttpClient();
HttpResponseMessage response = await client.SendAsync(request);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
string json = await response.Content.ReadAsStringAsync();
Root name = JsonConvert.DeserializeObject<Root>(json); //Deserializo el json para quedarme sólo con el pass
foreach(var i in name.Items)
{
if (pass == i.Pass)
{
Console.Write("Contrase?a CORRECTA");
displayNotication("Correcto");
}
else
{
Console.Write("Contrase?a INCORRECTA");
displayNotication("Incorrecto");
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/488542.html
上一篇:ObservableCollection<MyModel>看不到屬性
下一篇:Xamarin:“CustomBottomNavAppearance”未實作介面成員“IShellBottomNavViewAppearanceTracker.SetAppearance[...]”錯
