gpt4 book ai didi

c# - 如何解析包含 C# 列表的 Json WebApi 响应

转载 作者:太空宇宙 更新时间:2023-11-03 18:57:56 25 4
gpt4 key购买 nike

嗨,我有一个像

这样的 json 响应

{"Status":"Success","Message":"Authentication successful","Data":{"Key":"sdsdIRs99Iebe6QHmawlBsCks9mqfUt6jKYNQ%2bW","UserId":"ddjjj8-11e6-637af7"}}

我如何解析它以读取响应。

我是这样做的:

private void POST(string url) 
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";

System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();

postData="{\"UserName\": \"abc\"," +"\"Password\": \"mypwd\"}";

Byte[] byteArray = Encoding.UTF8.GetBytes(postData);

request.ContentLength = byteArray.Length;
request.ContentType = @"application/x-www-form-urlencoded";

using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}

long length = 0;

try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
length = response.ContentLength;
using (var reader = new StreamReader(response.GetResponseStream()))
{
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = reader.ReadToEnd();

string str= objText;
MyObject myojb = (MyObject)js.Deserialize(objText,typeof(MyObject));
}
}
}
catch (WebException ex)
{
// Log exception and throw as for GET example above
}
}

我能够读取“状态”和“消息”但无法读取“ key ”和“用户 ID”值。

请帮忙!

最佳答案

您可以使用 Newtonsoft Json 而不是 JavaScriptSerializer 您的 json 的类结构如下所示

public class Rootobject
{
public string Status { get; set; }
public string Message { get; set; }
public Data Data { get; set; }
}

public class Data
{
public string Key { get; set; }
public string UserId { get; set; }
}

反序列化可以很容易地完成,就像

Rootobject ro = JsonConvert.DeserializeObject<Rootobject>(json);

Console.WriteLine(ro.Status + ", " + ro.Message + ", " + ro.Data.Key + ", " + ro.Data.UserId);

关于c# - 如何解析包含 C# 列表的 Json WebApi 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41219330/

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