[
{
"Title": "TOY STORY 4",
"Genre": "COMEDY",
"Actors": [
"Tom Hanks",
"Tim Allen",
"Annie Potts"
],
"Id": 1
},
{
"Title": "The Matrix",
"Genre": "Action",
"Actors": [
"Keanu Reeves",
"Laurence Fishburne",
"Carrie-Anne Moss"
],
"Id": 2
}
]
Run Code Online (Sandbox Code Playgroud)
我有一个想要转换 C# 对象的 JSON 字符串:
public class Movies1
{
public string Title { get; set; }
public string Genre{ get; set; }
public List<Actor> Actors { get; set; }
public int id { get; set; }
}
public class Actor
{
public string Actors { get; set; }
public int Id { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我的反序列化代码:
List<movies> = JsonConvert.DeserializeObject<List<Movies1>>(json);
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
"ExceptionMessage": "无法从 System.String 转换或转换为 XXXXX.Models.Actor。", "ExceptionType": "System.ArgumentException", "StackTrace": " at Newtonsoft.Json.Utilities.ConvertUtils.EnsureTypeAssignable(Object)值,类型initialType,类型targetType)\r\n 在Newtonsoft.Json.Utilities.ConvertUtils.ConvertOrCast(对象initialValue,CultureInfo 区域性,类型targetType)\r\n 在Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureType(JsonReader reader,对象值、CultureInfo 文化、JsonContract 合约、Type targetType)"
看起来Actors是一个字符串列表,你需要的是这样的:
public class Movies1
{
public string Title { get; set; }
public string GENRE { get; set; }
public List<string> Actors { get; set; }
public int Id { get; set; }
}
public class Root
{
public List<Movies1> Movies { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
然后:
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
Run Code Online (Sandbox Code Playgroud)