我正在尝试调用两个 API 并存储它们的响应。以下是 API 响应类型:
API1 响应:
{
"Name": "Apple",
"Expiry": "2008-12-28T00:00:00",
"Price": 3.99,
"Sizes": [
"Small",
"Medium",
"Large"
]
}
API2 响应:
["Name=xyz, Id=1, Version=1","Name=abc, Id=1, Version=2","Name=hgf, Id=1, Version=3","Name=utgds, Id=1, Version=4","Name=kfgf, Id=2, Version=1"]
下面是调用 API 并获取结果集的代码。
var jsonObj = Get<SomeClass>("API_URL1");
var jsonObj2 = Get<Test>("API_URL2");
public T Get<T>(string requestUri)
{
T response = default(T);
using (var handler = new HttpClientHandler { Credentials = CredentialCache.DefaultNetworkCredentials })
{
using (var httpClient = CreateNewRequest(handler))
{
var httpTask = httpClient.GetAsync(requestUri);
var response = task.Result;
response.EnsureSuccessStatusCode();
if (response.IsSuccessStatusCode)
{
var result = response.Content.ReadAsStringAsync().Result;
var res = JsonConvert.DeserializeObject<T>(result);
}
}
}
return res;
}
private HttpClient CreateNewRequest(HttpClientHandler handler)
{
HttpClient client = new HttpClient(handler);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return client;
}
public class Test
{
public string Name { get; set; }
public int Id { get; set; }
public int Version { get; set; }
}
同样,我创建了一个类来保存 API1 响应。我能够存储 API1 响应但是在存储 API2 响应时我收到此错误消息。
无法将当前 JSON 数组(例如 [1,2,3])反序列化为类型,因为该类型需要 JSON 对象(例如 {"name":"value"})才能正确反序列化。要修复此错误,请将 JSON 更改为 JSON 对象(例如 {"name":"value"})或将反序列化类型更改为数组或实现集合接口的类型。
对此有什么想法/提示吗?
互换的青春
相关分类