我尝试使用JsonConvert库序列化JSON,但出现错误:
JsonSerializationException:无法将当前JSON数组(例如[1,2,3])反序列化为类型'APIConsume.Models.RootObject',因为该类型需要一个JSON对象(例如{“ name”:“ value”})正确反序列化。 要解决此错误,可以将JSON更改为JSON对象(例如{“ name”:“ value”}),也可以将反序列化类型更改为数组,或者将实现集合接口的类型(例如ICollection,IList)更改为List,例如List从JSON数组反序列化。还可以将JsonArrayAttribute添加到类型中,以强制其从JSON数组反序列化。
我得到的JSON是:
[{"id":0,"name":"Alice","image":"alice.jpg","fromLocation":"New York","toLocation":"Beijing"},{"id":1,"name":"Bob","image":"bob.jpg","fromLocation":"New Jersey","toLocation":"Boston"},{"id":2,"name":"Joe","image":"joe.jpg","fromLocation":"London","toLocation":"Paris"}]
我给出错误的代码行是:
RootObject rootObject = JsonConvert.DeserializeObject<RootObject>(apiResponse);
RootObject类由http://json2csharp.com/生成:
public class RootObject
{
public int id { get; set; }
public string name { get; set; }
public string image { get; set; }
public string fromLocation { get; set; }
public string toLocation { get; set; }
}
请帮助?
答案 0 :(得分:1)
尝试一下:
var rootObject = JsonConvert.DeserializeObject<List<RootObject>>(apiResponse);