De-serialize JSON return empty data

2019-06-13 03:38发布

问题:

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