反序列化JSON返回空数据 [英] De-serialize JSON return empty data
本文介绍了反序列化JSON返回空数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用api网址获取json响应
I use api url to get json response
http://localhost/WaWebService/Json/NodeDetail/Demo/SCADA_NODE_DEMO
使用Postman
软件,我确认有响应
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
}
}
之后我上课
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);
}
它在控制台上什么也没有.请帮助解决此问题.预先感谢.
It gives nothing on console. Please help to solve this issue. Advance thanks.
推荐答案
您应创建与响应json具有相同结构的类
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; }
}
然后像这样反序列化json
And then de-serialize json like this
DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(JsonResponse));
这篇关于反序列化JSON返回空数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文