我使用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
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);
}
它在控制台上什么都没有。请帮忙解决这个问题。提前谢谢。
答案 0 :(得分: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));