c# - How to read and deserialize IEnumerable of objects with httpclient
问题描述
I have a problem with reading and deserializing the HTTP response from my simple web API that supposes to return IEnumerable of ContactDto object. In contentReader.Read()
line I'm getting an error as:
"Data at the root level is invalid. Line 1, position 1."
Controller get code:
[HttpGet]
// GET api/<controller>
public IEnumerable<ContactDto> Get()
{
return new List<ContactDto>()
{
new ContactDto()
{
DateOfBirth = DateTime.Today,
FirstName = "tmp",
LastName = "tmp"
}
};
}
Model code:
public class ContactDto
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
}
Reading and parsing with HttpClient:
public IEnumerable<ContactDto> Read()
{
var serializer = new XmlSerializer(typeof(ContactDto));
var client =new HttpClient();
var stream = client.GetStreamAsync(_feedUrl).Result;
using (var streamReader = new StreamReader(stream))
{
using (var contentReader = new XmlTextReader(streamReader))
{
while (contentReader.Read())
{
var innerEventXml = contentReader.ReadAsString();
using (var stringReader = new StringReader(innerEventXml))
{
yield return (ContactDto) serializer.Deserialize(stringReader);
}
}
}
}
}
解决方案
Returning a list of objects in your Get
action results in a JSON result when calling it, not a XML result.
You can deserialize it using Newtonsoft.Json for example:
string result = client.GetStringAsync().Result;
return JsonConvert.Deserialize<List<ContactDto>>(result);
Althought I would suggest you to use await
for the async methods.
推荐阅读
- python - CSV Python输出:为列表中的每个项目输出一次而不是一次不匹配的字段
- pine-script - 检测图表上的最新信号
- c++ - 组合两个 QTransform 映射
- javascript - 在数字字段中写入时的 Javascript 事件
- excel - 用公式替换 G 列中的所有单元格
- javascript - is it possible to make an on(consolelog event? it would do something every time text is logged to console
- java - Cloud Run 优雅关闭
- python - 我如何使用其他字段来获取 jwt 令牌
- asp.net-core - 托管 .well-known/openid-configuration 的正确方法是什么?
- html - 哪些 HTML 元素是不可识别的?