Jaggi Jaggi - 3 months ago 10
JSON Question

How to deserialize JSON data in MVC

I'm new to deserializing JSON data
I'm getting follwing JSON data from responsebody of a service

"{\"Table\":[{\"SessionID\":\"DADF8335-31D3-401A-822F-6FCBF429DFC5\",\"Data\":\"80110144\",\"Expiration\":\"2016-08-25T21:22:51.683\"}]}"


When I try to deserialize and pass it to a variable it is showing null data.

This is my code in the controller and this is the variable 'ServiceInfo' getting null data

null data image

using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://sample.com");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync("SessionAPI/api/SessionMgmt/UseSession?SessionID=" + SessionID);

if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
SessionStoreID ServiceInfo = JsonConvert.DeserializeObject<SessionStoreID>(responseBody);

Response.Write(ServiceInfo.Data);
}
}


and this is my propery class

public class SessionStoreID
{
public string Session { get; set; }
public string Data { get; set; }
public DateTime ExpiredDate { get; set; }
}


Can some one guide on how to solve this

Answer

Your SessionStoreID class is incorrect so it will not map.

You need to do the following:

public class SessionStore
{
    [JsonProperty("Table")]
    public List<SessionStoreID> SessionStoreId { get; set;}
}

public class SessionStoreID
{
    [JsonProperty("SessionId")]
    public string Session { get; set; }
    public string Data { get; set; }
    [JsonProperty("Expiration")]
    public DateTime ExpiredDate { get; set; }
}


SessionStore ServiceInfo = JsonConvert.DeserializeObject<SessionStore>(responseBody);

You need to use the [JsonProperty(string)] attribute as your property names do not match the Json key names so it cannot automatically populate those fields in the object.