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

有帮助吗?

解决方案

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

其他提示

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top