JSON Deserialize Object HTTPWebResponse

妖精的绣舞 提交于 2021-01-29 03:56:01

问题


I am trying to take my Web Request JSON output and parse it. Here is the output

{
    "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"
        }
    ]
}

I have created public classes for these results

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

When I try to deserialize the Record class and choose the name, I get the name from the RootObject class. Here is my code

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:


You are trying to deserialize your JSON into the wrong class.

Change this line:

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

to this:

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

Fiddle: https://dotnetfiddle.net/2xR7hO



来源:https://stackoverflow.com/questions/38312627/json-deserialize-object-httpwebresponse

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