反序列化Json列出C# [英] Deserialize Json to List C#
问题描述
在反序列化api返回的Json时遇到一些问题.
I'm having some issues on deserializing a Json that the api returns.
Json如下:
{ "Result":[
{
"Id": 1,
"Type": "Type1"
},
{
"Id": 2,
"Type": "Type2"
}
]}
我正在尝试将其反序列化为这种类型的列表:
I'm trying to deserialize it to a list of this type:
public class ContactType
{
public int Id { get; set; }
public string Type { get; set; }
}
下面使用的ReturnType是:List< ContactType>和功能GetContactTypes的调用方式为:
The ReturnType used below is: List< ContactType > and the function GetContactTypes is called this way:
var test = await _items.GetContactTypes<List<ContactType>>(AuthToken.access_token);
使用此代码:
public async Task<ReturnType> GetContactTypes<ReturnType>(string access_token)
{
try
{
Header = string.Format("Bearer {0}", access_token);
client.DefaultRequestHeaders.Add("Authorization", Header);
HttpResponseMessage response = await client.GetAsync(base_url + "contacttypes");
if (response.StatusCode == HttpStatusCode.OK)
{
return JsonConvert.DeserializeObject<ReturnType>(await response.Content.ReadAsStringAsync());
}
else
{
return default(ReturnType);
}
}
catch (Exception ex)
{
return default(ReturnType);
}
}
但我总是会收到此错误:
But I always get this error:
无法将当前JSON对象(例如{"name":"value"})反序列化为类型'System.Collections.Generic.List`1',因为该类型需要JSON数组(例如[1,2 ,3])正确反序列化.
感谢您的帮助,谢谢.
推荐答案
您要反序列化的对象具有一个包含ContactType
数组的单个属性Result
-您的对象模型中没有该属性.尝试反序列化此对象:
The object you're trying to deserialize has a single property Result
containing the array of ContactType
- you dont have that in your object model. Try deserializing to this object:
public class MyClass // give this a more meaningful name
{
public List<ContactType> Result{ get; set; }
}
public class ContactType
{
public int Id { get; set; }
public string Type { get; set; }
}
然后:
...
var test = await _items.GetContactTypes<MyObject>(AuthToken.access_token);
...
这篇关于反序列化Json列出C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!