1

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

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

I always just use http://json2csharp.com/ to break my JSON down for me without having to think, and I can use this to build my Model exactly how it needs to be to match after I deserialize the JSON.

Model:

public class JSONModel
{
    public class Table
    {
        public string SessionID { get; set; }
        public string Data { get; set; }
        public DateTime Expiration { get; set; }
    }

    public class RootObject
    {
        public List<Table> Table { get; set; }
    }
}

Controller:

using System.Runtime.Serialization.Json;

    MemoryStream data = new MemoryStream(Encoding.UTF8.GetBytes(JSONstring));
    DataContractJsonSerializer serial = new DataContractJsonSerializer(typeof(List<JSONModel>));
    newjson = serial .ReadObject(data) as List<JSONModel>;

Comments

0

You can use DataContractJsonSerializer Class You can find an example from below How to serialize deserialize data

SessionStoreID serviceInfo = new SessionStoreID();
 MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(responseBody ));  
    DataContractJsonSerializer ser = new DataContractJsonSerializer(serviceInfo.GetType());  
    serviceInfo = ser.ReadObject(ms) as SessionStoreID ;  
    ms.Close();  

Comments

-1

you need to match the structure of the response. You can make your life easier by first casting to a dynamic object

JsonConvert.DeserializeObject<dynamic>(responseBody);

This gives you an object with the data in a structure you can replicate. You can compare the dynamic object to the one you want to use and make sure they match.

Once you've got the structure right, get rid of the dynamic cast and use your proper response class. This method gets more helpful as the responses get bigger and bigger, it is much easier to replicate an object you can see and inspect in debugger.

6 Comments

I would avoid deserializing the object to a dynamic type when you have the type available.
the whole point was to see the structure of the response and then match that to an actual class.
Why would you do that? That seems very unnecessary.
because if you can't tell from the first look what the structure should be then dynamic will take anything, create an object for you. it's a lot easier to match that object once you actually see it, to a concrete type. It's not an uncommon thing to do when you work with APIs especially when the response starts to get big.
man you keep missing the point completely. You debug things, I am not saying work with that forever, all I am saying is cast it like that first, make your class match that dynamic object then get rid of dynamic and you've got a successful cast without wasting your time.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.