JSON反序列化对象失败:无法将System.String转换为Model。

5
我正在尝试反序列化JSON,但仍然出现以下异常信息:
“无法将 System.String 转换为 SmartBookLibrary.ViewModel.BookJ1。”
描述:在当前网络请求的执行期间发生了未处理的异常。请查看堆栈跟踪以获取有关错误的详细信息以及错误在代码中的起源位置。异常详细信息: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);

这是我的模型或虚拟机:

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不匹配。那个JSON完整吗?在尝试反序列化之前,您很可能需要将该JSON转换为数组。 - Nkosi
1个回答

4
假设你展示的样本就是文件里的内容,那么在尝试反序列化之前,很可能需要将该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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接