【问题标题】:Deserialize json string and extract to model反序列化 json 字符串并提取到模型
【发布时间】:2020-10-23 15:30:38
【问题描述】:

我的 API 响应是一个 json 字符串,我需要使用反序列化和 IEnumerable 以某种方式将其转换为模型。

这是我的代码,在调试中我可以看到我返回的 json 字符串:

var responseString = await response.Content.ReadAsStringAsync();

但是,如果我尝试使用以下代码将其反序列化为其模型,则会收到构建错误...

productKeys = await JsonSerializer.DeserializeAsync
                     <IEnumerable<ProductKey>>(responseString);

错误是:

“无法将'string'转换为'System.IO.Stream'”

我该如何解决这个问题?

来自 cmets 的更新

这是我的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])来反序列化 正确

【问题讨论】:

  • 您确定在这行代码中遇到了构建错误吗?你能分享一个你试图反序列化的 json 样本吗?

标签: c# asp.net json .net-core json.net


【解决方案1】:

DeserializeAsync 是 System.Text.Json 中的一个方法,它实际上接受一个流,而不是一个字符串作为参数。

你已经有一个字符串,所以你应该能够使用DeserializeObject 反序列化字符串:

如果您使用的是 Newtonsoft.Json,则以下内容将反序列化:

// using Newtonsoft.Json
var productKeys = JsonConvert.DeserializeObject<IEnumerable<ProductKey>>(responseString);

更新来自您的 cmets:

对于您在评论中发布的 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; }
}

看来问题出在ProductKey 类中keyInfo 的定义上。

如果 JSON 仅包含单个 ProductKey,则可以省略 IEnumerable

var productKeys = JsonConvert.DeserializeObject<ProductKey>(responseString);

【讨论】:

  • 哈尔多。谢谢你。对不起,混乱的答复。我一般不使用 SO 所以学习。好吧,我已经取得了很大的进步。 Json 数据(数组)列表似乎需要 IENumerable。我的包含一个实体,因此重构代码以删除 IENumerable 让我到达了我需要的位置。我非常感谢您的指导。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-02
  • 2013-07-16
  • 1970-01-01
相关资源
最近更新 更多