c# - 反序列化 json 字符串并提取到模型
问题描述
我的 API 响应是一个 json 字符串,我需要以某种方式使用反序列化和 IEnumerable 将其转换为模型。
这是我的代码,在调试中我可以看到我返回的 json 字符串:
var responseString = await response.Content.ReadAsStringAsync();
但是,如果我尝试使用以下代码将其反序列化为其模型,则会收到构建错误...
productKeys = await JsonSerializer.DeserializeAsync
<IEnumerable<ProductKey>>(responseString);
错误是:
“无法将‘字符串’转换为‘System.IO.Stream’”
我怎样才能解决这个问题?
从评论更新
这是我的responseString
...
{
"success": 1,
"resultMessage": "Success",
"keyInfo": {
"trialKey": "46C8F3CBF2D09077D29325E55FAFCBFCBFF923CE2A2F3C189D49E4BC7FD9AA9A",
"goodTill": "2020-07-19",
"applyInstructions": "Use command GBLAPPKEY PRODUCT(MFT)to apply your trial key."
}
}
这是我的 ProductKey 模型...
public class ProductKey
{
public int success { get; set; }
public string resultMessage { get; set; }
public List<keyInfo> data { get; set; }
}
public class keyInfo
{
public string trialKey { get; set; }
public string goodTill { get; set; }
public string applyInstructions { get; set; }
}
这是错误...我相信它是说我的模型需要容纳一个数组,但是为什么呢?我没有在 JSON 中使用数组...?
JsonSerializationException:无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型 'System.Collections.Generic.IEnumerable`1[coreiWS.Models.ProductKey]' 因为该类型需要 JSON 数组(例如 [ 1,2,3]) 正确反序列化
解决方案
DeserializeAsync
是 System.Text.Json 中的一个方法,它实际上接受一个流,而不是一个字符串作为参数。
您已经有一个字符串,因此您应该能够使用以下方法反序列化字符串DeserializeObject
:
如果您使用的是 Newtonsoft.Json,则以下内容将反序列化:
// using Newtonsoft.Json
var productKeys = JsonConvert.DeserializeObject<IEnumerable<ProductKey>>(responseString);
从您的评论更新:
对于您在评论中发布的 JSON 字符串结果,您的ProductKey
类应如下所示:
public class ProductKey
{
public int success { get; set; }
public string resultMessage { get; set; }
public KeyInfo keyInfo { get; set; }
}
public class KeyInfo
{
public string trialKey { get; set; }
public string goodTill { get; set; }
public string applyInstructions { get; set; }
}
看起来问题出keyInfo
在ProductKey
类中的定义上。
如果 JSON 仅包含一个ProductKey
,则可以省略IEnumerable
:
var productKeys = JsonConvert.DeserializeObject<ProductKey>(responseString);
推荐阅读
- makefile - Make不应该重建深度依赖
- django - 使用过滤器查询在 Django 中找不到页面错误 {return Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')}
- c++ - 将 VS2010 项目从 32 位转换为 64 位时的 LNK2022
- mask - 在 Google 地球引擎中,如何从一个图像集合中选择与另一个图像集合中的选定像素值相对应的像素?
- javascript - 悬停在一条路径上时是否可以启动所有 SVG 关键帧动画?
- c# - Windows 运行时组件 C++ 结构/类返回到 UWP
- oracle - 无法过滤空日期时间值
- reactjs - 如何以可重用的方式为我的 material-ui 表创建选择过滤器?
- rabbitmq - RabbitMQ 保证传递到镜像队列
- reactjs - Material-UI Drawer 未在 Firefox 中显示