简体   繁体   中英

JSON DeserializeObject Could not cast or convert from System.String to Model

I'm trying to deserialize JSON, cut it keep showing me this exception:

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.

Here is sample of my 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"
}

Here is the Code:

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

Here is my Model Or 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; }
}

Assuming the shown sample is how it is in the file,

you most likely need to format that JSON as an array before trying to deserialize it

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

If however the shown sample is incomplete and the data in the file is actually stored as an array

[{
  "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"
}]

then you just need to deserialize to the correct type

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM