我试图反序列化JSON,继续向我展示这个异常:
无法从System.String转换为SmartBookLibrary.ViewModel.BookJ1。 描述:在执行当前web请求时发生了未处理的异常。请查看堆栈跟踪以获得有关错误的更多信息,以及它起源于代码的位置。 异常详细信息: System.ArgumentException:无法从System.String转换为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);下面是我的模型(VM):
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; }
}发布于 2019-03-06 17:04:25
假设显示的示例是文件中的样子,
在试图反序列化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);https://stackoverflow.com/questions/55028399
复制相似问题