De-serialize JSON return empty data

旧城冷巷雨未停 提交于 2019-12-08 12:15:51

问题


I use api url to get json response

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

Using Postman software I verify there is response

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

After it I make class

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

Now, I de-serialize the json object using DataContractJsonSerializer

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

It gives nothing on console. Please help to solve this issue. Advance thanks.


回答1:


You should create class that have same structure as response 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; }
}

And then de-serialize json like this

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


来源:https://stackoverflow.com/questions/46294262/de-serialize-json-return-empty-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!