JSON字符串反序列化失败:requires a JSON array (e.g. [1,2,3])
Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.List`1……
because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'data', line 1, position 8.
首先看【JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.List`】,我们把一个{}放进[]里,肯定解析失败了a
其次认真分析json字符串的结构与对象是不是结构不匹配。
最后就是重新调试.
class Car
{
public string Code { get; set; }
public string Name { get; set; }
public string Color { get; set; }
}
List<Car> carList = new List<Car>();
carList.Add(new Car() { Code = "H9Plus", Name = "新红旗H9+", Color = "银色" });
carList.Add(new Car() { Code = "LX21", Name = "2021款理想ONE", Color = "黑色" });
string jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(carList);
//[{"Code":"H9Plus","Name":"新红旗H9+","Color":"银色"},{"Code":"LX21","Name":"2021款理想ONE","Color":"黑色"}]
//错误的解析
Car car = Newtonsoft.Json.JsonConvert.DeserializeObject<Car>(jsonString);//抛出异常 Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.List`1
//正确的解析
List<Car> newCarList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Car>>(jsonString);
更多推荐
所有评论(0)