+-

我正在尝试反序列化 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);
这是我的模型或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; }
}
最佳答案
假设显示的示例是文件中的示例,
您很可能需要在尝试反序列化该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);
点击查看更多相关文章
转载注明原文:JSON DeserializeObject无法转换或从System.String转换为Model - 乐贴网