Question

My first attempt and JSON desrialization and I'm stuck, just wondering if you could help?

I have the following JSON

{
    "summary":{
        "pricing":{
            "net":988,
            "tax":13,
            "gross":729
        },
        "status":{
            "runningfor":29881175,
            "stoppedfor":88805,
            "idlefor":1298331744
        }
    }
}

here my c# code

private void MakeRequest()
{
    HttpWebRequest request = WebRequest.Create(Url) as HttpWebRequest; 
    request.Method = "GET";
    request.ContentType = "application/x-www-form-urlencoded";
    request.Credentials = new NetworkCredential(Username, Password);
    request.Headers.Add(string.Format("App-Key: {0}", ApiKey));

    using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
    {
        StreamReader reader = new StreamReader(response.GetResponseStream());
        string resutls = reader.ReadToEnd();
        Response.Write(resutls);
        Status status = JSONHelper.JsonDeserialize<Status>(resutls);
        Response.Write(status.RunningFor);
    }
}

public class JSONHelper
{
    /// <summary>
    /// JSON Deserialization
    /// </summary>
    public static T JsonDeserialize<T>(string jsonString)
    {
        T obj = Activator.CreateInstance<T>();
        MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString));
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
        obj = (T)serializer.ReadObject(ms);
        ms.Close();
        return obj;
    }
}


[DataContractAttribute(Name = "status")]
public class Status
{
    [DataMember(Name = "runningfor")]
    public int RunningFor{ get; set; }
    [DataMember(Name = "stoppedfor")]
    public int StoppedFor{ get; set; }
    [DataMember(Name = "idlefor")]
    public int IdleFor{ get; set; }
}

And I'm only interested in the status result nothing else at all. what am I doing wrong as it is only returning 0 for RunningFor.

Thanks In advance

Was it helpful?

Solution

You need to deserialize into a structure which maps to the whole JSON you're trying to deserialize, not only to the part you want. In your case, the code below shows one way of doing it.

public class StackOverflow_9135439
{
    const string JSON = @"{
    ""summary"":{
        ""pricing"":{
            ""net"":988,
            ""tax"":13,
            ""gross"":729
        },
        ""status"":{
            ""runningfor"":29881175,
            ""stoppedfor"":88805,
            ""idlefor"":1298331744
        }
    }
}";
    [DataContractAttribute(Name = "status")]
    public class Status
    {
        [DataMember(Name = "runningfor")]
        public int RunningFor { get; set; }
        [DataMember(Name = "stoppedfor")]
        public int StoppedFor { get; set; }
        [DataMember(Name = "idlefor")]
        public int IdleFor { get; set; }
    }

    [DataContract]
    public class Summary
    {
        [DataMember(Name = "status")]
        public Status Status { get; set; }

        // add "pricing" later if you need
    }

    [DataContract]
    public class Response
    {
        [DataMember(Name = "summary")]
        public Summary Summary { get; set; }
    }

    public class JSONHelper
    {
        /// <summary>
        /// JSON Deserialization
        /// </summary>
        public static T JsonDeserialize<T>(string jsonString)
        {
            T obj = Activator.CreateInstance<T>();
            MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString));
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
            obj = (T)serializer.ReadObject(ms);
            ms.Close();
            return obj;
        }
    }

    public static void Test()
    {
        Response resp = JSONHelper.JsonDeserialize<Response>(JSON);
        Console.WriteLine(resp.Summary.Status.RunningFor);
    }
}

OTHER TIPS

The DataContractJsonSerializer is case-sensitive. Use "runningfor".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top