Newtonsoft.Json 序列化
当我们对一个json数组进行反序列化用Newtonsoft.Json.JsonConvert.DeserializeObject<T>() 通常会报此错误
Newtonsoft.Json.dll 中发生,但未在用户代码中进行处理
其他信息: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'MyHttp.Controllers.ValuesController+ProvinceModel' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path '', line 1, position 1.
1 public void PostProvince() 2 { 3 var retString = "[{\"ProvinceName\":\"湖北省\"},{\"ProvinceName\":\"河北省\"}]"; 4 var provinces = Newtonsoft.Json.JsonConvert.DeserializeObject<ProvinceModel>(retString); 5 } 6 7 8 public class ProvinceModel 9 { 10 public string ProvinceName { get; set; }13 }
解决方案
1 public void PostProvince() 2 { 3 var retString = "[{\"ProvinceName\":\"湖北省\"},{\"ProvinceName\":\"河北省\"}]"; 4 var provinces = Newtonsoft.Json.JsonConvert.DeserializeObject<List<ProvinceModel>>(retString); 5 }