嵌套数据的反序列化

发布于 2025-01-02 07:20:30 字数 1945 浏览 1 评论 0原文

我的第一次尝试和 JSON 反序列化,我陷入困境,只是想知道你是否可以提供帮助?

有以下 JSON

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

我的 C# 代码

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

,我只对状态结果感兴趣,没有其他任何兴趣。我做错了什么,因为它只为 RunningFor 返回 0。

提前致谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

你对谁都笑 2025-01-09 07:20:30

您需要反序列化为一个结构,该结构映射到您尝试反序列化的整个 JSON,而不仅仅是您想要的部分。对于您的情况,下面的代码显示了一种实现方法。

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

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);
    }
}
吹梦到西洲 2025-01-09 07:20:30

DataContractJsonSerializer 区分大小写。使用“跑步”。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文