我正在嘗試反序列化我在 Web Api 上擁有的類別串列。但它不會回傳任何東西。
首先它回傳了這種型別的錯誤
Cannot deserialize the JSON array (e.g. [1,2,3]) into type ' ' because type requires JSON object (e.g. {“name”:“value”}) to deserialize correctly
我通過不使用等待來修復它。現在我的變數jsonResponse回傳一切都很好,但變數result為空。
這是我的代碼錯誤所在
// Generic Get Method
private async Task<T> HttpGetAsync<T>(string url, string token)
{
T result = default(T);
try
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
HttpResponseMessage response = httpClient.GetAsync(url).Result;
HttpContent content = response.Content;
if (response.IsSuccessStatusCode)
{
var jsonResponse = await content.ReadAsStringAsync();
result = JsonConvert.DeserializeObject<T>(jsonResponse);
}
else
{
throw new Exception(((int)response.StatusCode).ToString() " - " response.ReasonPhrase);
}
}
catch (Exception ex)
{
one rror(ex.ToString());
}
return result;
}
這是我的 json 回傳的內容
{
"data": [
{
"id": 1,
"name": "Alianzas"
},
{
"id": 2,
"name": "Pendientes"
},
{
"id": 3,
"name": "Pulseras"
},
{
"id": 4,
"name": "Colgantes"
},
{
"id": 5,
"name": "Gargantillas"
},
{
"id": 6,
"name": "Relojes"
}
],
"meta": {
"totalCount": 6,
"pageSize": 20,
"currentPage": 1,
"totalPages": 1,
"hasNextPage": false,
"hasPreviousPage": false
}
}
我不知道發生了什么事。請幫忙。
uj5u.com熱心網友回復:
它對我有用,雖然我沒有復制你的 HTTP 內容。只要您的代碼真正回傳您發布到jsonResponse字串 var 中的 json,那么我看不出問題:
class Program
{
static async Task Main(string[] args)
{
var x = await new Program().HttpGetAsync<SomeNamespace.SomeRoot>("", "");
}
private async Task<T> HttpGetAsync<T>(string url, string token)
{
T result = default(T);
try
{
//httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
//HttpResponseMessage response = httpClient.GetAsync(url).Result;
// HttpContent content = response.Content;
if (/*response.IsSuccessStatusCode*/true)
{
//var jsonResponse = await content.ReadAsStringAsync();
var jsonResponse = @"{
""data"": [
{
""id"": 1,
""name"": ""Alianzas""
},
{
""id"": 2,
""name"": ""Pendientes""
},
{
""id"": 3,
""name"": ""Pulseras""
},
{
""id"": 4,
""name"": ""Colgantes""
},
{
""id"": 5,
""name"": ""Gargantillas""
},
{
""id"": 6,
""name"": ""Relojes""
}
],
""meta"": {
""totalCount"": 6,
""pageSize"": 20,
""currentPage"": 1,
""totalPages"": 1,
""hasNextPage"": false,
""hasPreviousPage"": false
}
}";
result = JsonConvert.DeserializeObject<T>(jsonResponse);
}
else
{
//throw new Exception(((int)response.StatusCode).ToString() " - " response.ReasonPhrase);
}
}
catch (Exception ex)
{
//OnError(ex.ToString());
}
return result;
}
}
}
namespace SomeNamespace
{
using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public partial class SomeRoot
{
[JsonProperty("data")]
public Datum[] Data { get; set; }
[JsonProperty("meta")]
public Meta Meta { get; set; }
}
public partial class Datum
{
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
}
public partial class Meta
{
[JsonProperty("totalCount")]
public long TotalCount { get; set; }
[JsonProperty("pageSize")]
public long PageSize { get; set; }
[JsonProperty("currentPage")]
public long CurrentPage { get; set; }
[JsonProperty("totalPages")]
public long TotalPages { get; set; }
[JsonProperty("hasNextPage")]
public bool HasNextPage { get; set; }
[JsonProperty("hasPreviousPage")]
public bool HasPreviousPage { get; set; }
}
public partial class SomeRoot
{
public static SomeRoot FromJson(string json) => JsonConvert.DeserializeObject<SomeRoot>(json, SomeNamespace.Converter.Settings);
}
public static class Serialize
{
public static string ToJson(this SomeRoot self) => JsonConvert.SerializeObject(self, SomeNamespace.Converter.Settings);
}
internal static class Converter
{
public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None,
Converters =
{
new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
},
};
}
由http://app.quicktype.io準備的 JSON 接收器類- 無從屬關系
uj5u.com熱心網友回復:
嘗試使用 List<Category> 作為 T 類
var result = await HttpGetAsync<List<Category>> (url, token)
......
if (response.IsSuccessStatusCode)
{
var jsonResponse = await content.ReadAsStringAsync();
var jsonParsed=JObject.Parse(jsonResponse);
result =jsonResponse["data"].ToObject<T>();
}
班級
public partial class Category
{
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
....another properties
}
或者如果您需要元資料,請使用類別作為 T
var result = await HttpGetAsync<Categories> (url, token)
....
var result = JsonConvert.DeserializeObject<T>(jsonResponse);
班級
public class Categories
{
[JsonProperty("data")]
public List<Category> Data {get; set;}
[JsonProperty("meta")]
public Meta Meta {get; set;}
}
public partial class Meta
{
[JsonProperty("totalCount")]
public long TotalCount { get; set; }
[JsonProperty("pageSize")]
public long PageSize { get; set; }
[JsonProperty("currentPage")]
public long CurrentPage { get; set; }
[JsonProperty("totalPages")]
public long TotalPages { get; set; }
[JsonProperty("hasNextPage")]
public bool HasNextPage { get; set; }
[JsonProperty("hasPreviousPage")]
public bool HasPreviousPage { get; set; }
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/466778.html
標籤:C# 网 json xamarin 视觉工作室 2019
