首页 > 解决方案 > 反序列化 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]) 正确反序列化

标签: c#asp.netjson.net-corejson.net

解决方案


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; }
}

看起来问题出keyInfoProductKey类中的定义上。

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

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

推荐阅读