2

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.

stefankmitph
  • 3,236
  • 2
  • 18
  • 22
Samir Rawat
  • 53
  • 1
  • 2
  • 8
  • could you post your `JClass` model? – stefankmitph Apr 27 '15 at 12:50
  • possible duplicate of [Using JsonConvert.DeserializeObject to deserialize Json to a C# POCO class](http://stackoverflow.com/questions/11126242/using-jsonconvert-deserializeobject-to-deserialize-json-to-a-c-sharp-poco-class) – evanmcdonnal Apr 27 '15 at 20:46

6 Answers6

12

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.

Krunal Mevada
  • 1,637
  • 1
  • 17
  • 28
  • hey one question, what is ["logInResult"] ? used as string? –  Jan 23 '16 at 18:24
  • 1
    @NathielPaulino "logInResult" is nothing but json string JArray key. For more clarification please see `"logInResult": [` in posted question. Hope you now clear. – Krunal Mevada Jan 29 '16 at 04:33
  • @KrunalMevada This helped me with my project. Thanks. This should def. be marked as the answer. – Lahib Apr 14 '16 at 12:40
9

You should create the following classes in order to map your json data to actual classes.

    public class LogInResult
{
    public string Name { get; set; }
    public string cityName { get; set; }
    public string img { get; set; }
    public string usrId { get; set; }
}

public class RootObject
{
    public List<LogInResult> logInResult { get; set; }
}

You can then store the RootObject for further processing:

var result = JsonConvert.DeserializeObject<RootObject>(jsonString);

By using the getter for the list, you can get the list and iterate it as usual.

typie34
  • 358
  • 4
  • 12
3

Your question seems to be a duplicate of: Using JsonConvert.DeserializeObject to deserialize Json to a C# POCO class


You are trying to deserialize your JSON object into an JSON array.

Store just the content of logInResult into jsonString, that is:

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

This of course assumes that you got your JClass correct in the first place.

Community
  • 1
  • 1
Jack Miller
  • 6,843
  • 3
  • 48
  • 66
0

You're C# code thinks it is reading this:

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

i.e. an array of objects, when in fact it is reading an object with a property logInResult, which is an array.

garryp
  • 5,508
  • 1
  • 29
  • 41
0

I have faced the same issue, just wanted to point out when there is an array or list exist in JSON like in logInResults is a list of a type, so while deserializing JSON convert is not able to understand that, so what you can do it create your model in this way.

Class  giveName
{
  givenName[] logInResult {get;set;}         // can use list also will work fine
}

public class giveName2
{
   public string Name {get;set;}
   public string cityName {get;set;}
   public string img {get;set;}
   public string usrId {get;set;}
}

i will tell you why because see the first curly braces of your json object for that to work, you must have created a type(class) which has a property named logInResult, in the same way object of which the list is made up has to be provided a type and then the properties matching with list items

Note: giveName and giveName2 is the name you can give yourself it wont matter with class name

0

Convert to collection of object

using Newtonsoft.Json.Linq;

JObject obj = JObject.Parse(jsonString);
JArray arr = (JArray)obj["logInResult"];
IList<JClass> student= arr.ToObject<IList<JClass>>();

return View(student);

Then iterate over it.

IEnumerable<Student>
  @foreach (var item in Model)
 {
   item.Name
   item.CityName
   item.Img
   item.UsrId
 }
Jay
  • 147
  • 2
  • 4