JSON反序列化对象HTTPWebResponse

时间:2016-07-11 17:17:11

标签: c# json json.net

我正在尝试获取Web请求JSON输出并解析它。这是输出

{
    "kind":"internal",
    "name":"SplashPageToggle_dg",
    "fullPath":"SplashPageToggle_dg",
    "generation":1255326,
    "selfLink":"https://link",
    "type":"stri ng",
    "records":[
        {
            "name":"enable_app1",
            "data":"0"
        },
        {
            "name":"enable_app2",
            "da ta":"0"
        },
        {
            "name":"enable_app3",
            "data":"0"
        },
        {
            "name":"enable_app4",
            "data":"0"
        },
        {
            "name":"enable_app5",
            "data":"0"
        },
        {
            "name":"enable_app6",
            "data":"1"
        },
        {
            "name":"enable_app7",
            "data":"0"
        },
        {
            "name":"enable_app8",
            "data":"0"
        },
        {
            "name":"enable_app9",
            "data":"0"
        },
        {
            "name":"enable_app10",
            "data":"0"
        }
    ]
}

我为这些结果创建了公共类

public class RootObject
{
   public string kind { get; set; }
   public string name { get; set; }
   public string fullPath { get; set; }
   public int generation { get; set; }
   public string selfLink { get; set; }
   public string type { get; set; }
   public List<Record> records { get; set; }
}

public class Record
{
   public string name { get; set; }
   public string data { get; set; }
}

当我尝试反序列化Record类并选择名称时,我从RootObject类中获取名称。这是我的代码

static void Main(string[] args)
{
   string url = "URL";    
   HttpWebRequest getRequest = (HttpWebRequest)WebRequest.Create(url);
   getRequest.Method = "GET";
   getRequest.Credentials = new NetworkCredential("UN", "PW");   
   ServicePointManager.ServerCertificateValidationCallback = new
      RemoteCertificateValidationCallback
      (
         delegate { return true; }
      );

   var getResponse = (HttpWebResponse)getRequest.GetResponse();    
   Stream newStream = getResponse.GetResponseStream();
   StreamReader sr = new StreamReader(newStream);    
   var result = sr.ReadToEnd();    
   var splashInfo = JsonConvert.DeserializeObject<Record>(result);

   Console.WriteLine(splashInfo.name);
   Console.ReadLine();
}

1 个答案:

答案 0 :(得分:4)

您正在尝试将JSON反序列化为错误的类。

更改此行:

var splashInfo = JsonConvert.DeserializeObject<Record>(result);

到此:

var splashInfo = JsonConvert.DeserializeObject<RootObject>(result);

小提琴:https://dotnetfiddle.net/2xR7hO