gpt4 book ai didi

c# - 在 C# 中使用索引数组反序列化 JSON

转载 作者:太空狗 更新时间:2023-10-29 20:34:22 26 4
gpt4 key购买 nike

我是使用 JSON 的新手,正在处理来自 API 的返回,我无法更改其格式。返回示例是:(实际 url 已被删除)

{
"body":
{
"link":
{"linkurl": ["www.google.com"]}
},
"error": null,
"message": "Data Retrieved successfully",
"status": true
}

我在 VS2010 中使用带有 MVC 3 的 Newtonsoft.Json 库。

我的类(class)是:

[JsonObject(MemberSerialization.OptIn)]
public class LinksJSON
{
[JsonProperty]
public string link{ get; set; }

[JsonProperty]
public string message { get; set; }

[JsonProperty]
public string error { get; set; }

[JsonProperty]
public bool status { get; set; }
}

我反序列化它:

private static T _download_serialized_json_data<T>(string url) where T : new()
{
using (var w = new WebClient())
{
var json_data = string.Empty;
// attempt to download JSON data as a string
try
{
json_data = w.DownloadString(url);
}
catch (Exception) { }
// if string with JSON data is not empty, deserialize it to class and return its instance
return !string.IsNullOrEmpty(json_data) ? JsonConvert.DeserializeObject<T>(json_data) : new T();
}
}

public string CheckJSONLink()
{

var url = "<api url-removed for security>";

var outObj = _download_serialized_json_data<LinksJSON>(url);



return outObj.Link;
}

不过,我正在尝试获取 linkurl 的值,它是 Link 中的索引数组。

我将如何访问这些信息?

最佳答案

你没有设置你的类来匹配 JSON,你的类说 link 是一个简单的字符串,你的例子显示它是一个复杂的类型。

为了按照您的预期正确反序列化它,您必须修改您的类以匹配 JSON。具体来说,link 应该是一个类的实例。

关于c# - 在 C# 中使用索引数组反序列化 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13729820/

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