gpt4 book ai didi

c# - JSON DeserializeObject 无法从 System.String 转换或转换为模型

转载 作者:行者123 更新时间:2023-11-30 16:38:23 24 4
gpt4 key购买 nike

我正在尝试反序列化 JSON,但它一直向我显示此异常:

Could not cast or convert from System.String to SmartBookLibrary.ViewModel.BookJ1.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentException: Could not cast or convert from System.String to SmartBookLibrary.ViewModel.BookJ1.

这是我的 JSON 示例:

{
"authorfamily1": "von Goethe",
"authorname1": "Johann",
"authorsurname1": "Wolfgang",
"title": "Fausto I",
"extension": "epub",
"md5": "58cb1dd438bc6c6027fcda9e7729e5ee",
"isbn": "",
"descr": "",
"cover": "1"
},
{
"authorfamily1": "von Goethe 1",
"authorname1": "Johann",
"authorsurname1": "Wolfgang",
"title": "Fausto I",
"extension": "epub",
"md5": "58cb1dd438bc6c6027fcda9e7729e5ee",
"isbn": "",
"descr": "",
"cover": "1"
}

代码如下:

var json = System.IO.File.ReadAllText("/data1.json");           
var courses = JsonConvert.DeserializeObject<Dictionary<string, BookJ1>>(json);

这是我的模型或虚拟机:

public class BookJ1
{
public string title { get; set; }
public string isbn { get; set; }
public string extension { get; set; }
public string authorfamily1 { get; set; }
public string authorname1 { get; set; }
public string md5 { get; set; }
public int cover { get; set; }
[AllowHtml]
[Column(TypeName = "text")]
public string descr { get; set; }
}

最佳答案

假设显示的示例是文件中的样子,

在尝试反序列化之前,您很可能需要将该 JSON 格式化为数组

var data = System.IO.File.ReadAllText("/data1.json");
var json = string.Format("[{0}]", data);
BookJ1[] courses = JsonConvert.DeserializeObject<BookJ1[]>(json);

但是如果显示的示例不完整并且文件中的数据实际上存储为数组

[{
"authorfamily1": "von Goethe",
"authorname1": "Johann",
"authorsurname1": "Wolfgang",
"title": "Fausto I",
"extension": "epub",
"md5": "58cb1dd438bc6c6027fcda9e7729e5ee",
"isbn": "",
"descr": "",
"cover": "1"
},
{
"authorfamily1": "von Goethe 1",
"authorname1": "Johann",
"authorsurname1": "Wolfgang",
"title": "Fausto I",
"extension": "epub",
"md5": "58cb1dd438bc6c6027fcda9e7729e5ee",
"isbn": "",
"descr": "",
"cover": "1"
}]

然后你只需要反序列化为正确的类型

var json = System.IO.File.ReadAllText("/data1.json");           
BookJ1[] courses = JsonConvert.DeserializeObject<BookJ1[]>(json);

关于c# - JSON DeserializeObject 无法从 System.String 转换或转换为模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55028399/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com