JSON DeserializeObject无法转换或从System.String转换为Model

时间:2019-03-06 16:57:39

标签: c# asp.net-mvc

我正在尝试反序列化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; }
}

1 个答案:

答案 0 :(得分:2)

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

您最有可能需要先将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);