Newtonsoft 无法反序列化对象
Newtonsoft can't deserialize object
我正在尝试反序列化我在网络上的类别列表 Api。但它不会 return 任何东西。
首先是 return 这种类型的错误
Cannot deserialize the JSON array (e.g. [1,2,3]) into type ' ' because type requires JSON object (e.g. {“name”:“value”}) to deserialize correctly
我通过不使用 await 修复了它。现在在我的变量 jsonResponse
return 上一切正常,但变量 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)
{
OnError(ex.ToString());
}
return result;
}
这是我的 json returns
{
"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
}
}
我不知道发生了什么。请帮忙。
它对我有用,尽管我没有复制您的 HTTP 内容。只要你的代码真正 returns 你发布到 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 }
},
};
}
JSON 接收者 类 由 http://app.quicktype.io 准备 - 无隶属关系
尝试使用 List < Category > 作为 T class
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>();
}
class
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);
classes
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; }
}
我正在尝试反序列化我在网络上的类别列表 Api。但它不会 return 任何东西。
首先是 return 这种类型的错误
Cannot deserialize the JSON array (e.g. [1,2,3]) into type ' ' because type requires JSON object (e.g. {“name”:“value”}) to deserialize correctly
我通过不使用 await 修复了它。现在在我的变量 jsonResponse
return 上一切正常,但变量 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)
{
OnError(ex.ToString());
}
return result;
}
这是我的 json returns
{
"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
}
}
我不知道发生了什么。请帮忙。
它对我有用,尽管我没有复制您的 HTTP 内容。只要你的代码真正 returns 你发布到 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 }
},
};
}
JSON 接收者 类 由 http://app.quicktype.io 准备 - 无隶属关系
尝试使用 List < Category > 作为 T class
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>();
}
class
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);
classes
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; }
}