【问题标题】:De-serialize JSON return empty data反序列化 JSON 返回空数据
【发布时间】:2017-09-19 07:18:28
【问题描述】:

我使用 api url 来获取 json 响应

http://localhost/WaWebService/Json/NodeDetail/Demo/SCADA_NODE_DEMO

使用Postman 软件我验证有响应

{
    "Result": {
        "Ret": 0
    },
    "Node": {
        "ProjectId": 1,
        "NodeId": 1,
        "NodeName": "SCADA_NODE_DEMO",
        "Description": "",
        "Address": "SALMAN-MUSHTAQ",
        "Port1": 0,
        "Port2": 0,
        "Timeout": 0
    }
}

之后我上课了

class Result
    {
        public int Ret { get; set; }
    }

    public class Node
    {
        public int ProjectId { get; set; }
        public int NodeId { get; set; }
        public string NodeName { get; set; }
        public string Description { get; set; }
        public string Address { get; set; }
        public int Port1 { get; set; }
        public int Port2 { get; set; }
        public int Timeout { get; set; }
    }

现在,我使用 DataContractJsonSerializer 反序列化 json 对象

var client = new WebClient { Credentials = new NetworkCredential("username", "password") };


                string json = client.DownloadString(url);
                using(var ms = new MemoryStream (Encoding.Unicode.GetBytes(json)))
                {
                    DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(Node));
                    Node nObj = (Node)deserializer.ReadObject(ms);
                    Console.WriteLine("Node name: " + nObj.NodeName);
                }

它在控制台上什么也没有。请帮助解决这个问题。提前谢谢。

【问题讨论】:

  • 我也尝试使用 Json.Net 和 JavaScriptSerializer,但我遇到了同样的问题。请高手帮忙。

标签: json datacontractjsonserializer


【解决方案1】:

您应该创建与响应 json 具有相同结构的类

class JsonResponse
{
    public Result Result { get; set; }
    public Node Node { get; set; }
}

class Result
{
    public int Ret { get; set; }
}

public class Node
{
    public int ProjectId { get; set; }
    public int NodeId { get; set; }
    public string NodeName { get; set; }
    public string Description { get; set; }
    public string Address { get; set; }
    public int Port1 { get; set; }
    public int Port2 { get; set; }
    public int Timeout { get; set; }
}

然后像这样反序列化json

DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(JsonResponse)); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-03
    • 1970-01-01
    • 1970-01-01
    • 2021-06-14
    • 2015-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多