无法反序列化当前JSON对象(例如{"name":"value"}) [英] Cannot deserialize the current JSON object (e.g. {"name":"value"})
问题描述
这是我的JSON数据
{
"logInResult": [
{
"Name": "yogesh singh",
"cityName": "",
"img": "DefaultImage/D_Vp_Men.png",
"usrId": "374"
}
]
}
这是我的代码
public async Task<ActionResult> Index()
{
HttpClient webClient1 = new HttpClient();
Uri uri = new Uri("http://m.vinipost.com/service/userprofile.svc/logIn?loginId=thyschauhan@gmail.com&pass=12345");
HttpResponseMessage response1;
response1 = await webClient1.GetAsync(uri);
var jsonString = await response1.Content.ReadAsStringAsync();
var _Data = JsonConvert.DeserializeObject<List<JClass>>(jsonString);
foreach (JClass Student in _Data)
{
ViewBag.Message += Student.Name + ", ";
}
dynamic obj = JsonConvert.DeserializeObject(jsonString);
ViewBag.Message += obj.data.Name;
return View();
}
错误是
无法将当前JSON对象(例如{"name":"value"})反序列化为类型'System.Collections.Generic.List`1 [MvcSumit1.Models.JClass]',因为该类型需要JSON数组(例如[1,2,3])正确反序列化. 要解决此错误,可以将JSON更改为JSON数组(例如[1,2,3]),也可以更改反序列化类型,使其成为普通的.NET类型(例如,不像整数这样的原始类型,也不像这样的集合类型.数组或列表),可以从JSON对象反序列化.还可以将JsonObjectAttribute添加到类型中,以强制其从JSON对象反序列化. 路径"logInResult",第1行,位置15.
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[MvcSumit1.Models.JClass]' 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) 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 'logInResult', line 1, position 15.
推荐答案
您不能使用JsonConvert.DeserializeObject.
请尝试以下代码:
JObject jsonResponse = JObject.Parse(jsonString);
JObject objResponse = (JObject)jsonResponse["logInResult"];
Dictionary<string, JArray> _Data = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, JArray>>(objResponse.ToString());
希望这会对您有所帮助.
Hope this will help you.
这篇关于无法反序列化当前JSON对象(例如{"name":"value"})的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!