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);

 

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值