gpt4 book ai didi

c# - JSON 反序列化对象 HTTPWebResponse

转载 作者:太空宇宙 更新时间:2023-11-03 21:10:03 24 4
gpt4 key购买 nike

我正在尝试获取我的 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)类

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

最佳答案

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

改变这一行:

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

为此:

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

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

关于c# - JSON 反序列化对象 HTTPWebResponse,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38312627/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com