Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
729 views
in Technique[技术] by (71.8m points)

c# - Cannot deserialize the current JSON object (e.g. {"name":"value"})

This is my JSON data

{
    "logInResult": [
        {
            "Name": "yogesh singh",
            "cityName": "",
            "img": "DefaultImage/D_Vp_Men.png",
            "usrId": "374"
        }
    ]
}

and this is my code

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

and the error is

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can't directly deserialize from your API response using JsonConvert.DeserializeObject.

Try this below code :

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...