【发布时间】:2020-02-17 09:16:17
【问题描述】:
我有一个具有自己对象类型的函数:
public RaceJson GetLatestRace()
{
string filter = "example";
List<RaceJson> currentRace = await gsaClient.SendCustomRequest<List<RaceJson>>("races?$filter=" + filter);
return currentRace.FirstOrDefault();
}
我想使用他们都会使用的通用函数。我希望它是通用的,并将对象反序列化为我发送的类型。我目前有:
public async Task<T> SendCustomRequest<T>(string odataFilter)
{
string response = await SendRequestAsync(odataFilter, true);
if( !string.IsNullOrEmpty(response))
{
T converted = JsonConvert.DeserializeObject<T>(response);
return converted;
}
return default;
}
尝试反序列化列表时出现错误:
JsonSerializationException: 无法反序列化当前 JSON 对象 (例如 {"name":"value"}) 转换为类型 'System.Collections.Generic.List`1[tf_gsa_client.Models.HorseRacing.RaceJson]' 因为该类型需要一个 JSON 数组(例如 [1,2,3])来反序列化 正确。要修复此错误,请将 JSON 更改为 JSON 数组 (例如 [1,2,3])或更改反序列化类型,使其成为正常的 .NET 类型(例如,不是像整数这样的原始类型,也不是集合 可以从 JSON 反序列化的数组或列表等类型 目的。 JsonObjectAttribute 也可以添加到类型中来强制它 从 JSON 对象反序列化。
谢谢。
【问题讨论】:
-
你说错了是什么意思?
-
@DavidPilkington 问题已更新
-
调用
SendCustomRequest时缺少类型 -
你应该传入你想要反序列化的类型。
SendCustomRequest<RaceJson>
标签: c# json object serialization types