【问题标题】:C# http-get url JSON data and parse it to text..?C# http-get url JSON 数据并将其解析为文本..?
【发布时间】:2021-12-12 17:32:55
【问题描述】:

我真的不知道怎么问这个,但基本上,

我有一个网址http://URL.com/filename.json 我想从/filename.json 获取数据并“将其转换为文本”。 url 文件包含以下内容:{"CurrentVersion": "1.0"} 我想获取 CurrentVersion 并定义一个字符串,其值为 (1.0)。

【问题讨论】:

  • 所以您想将 JSON 反序列化为可以读取 CurrentVersion 值的对象?
  • 请包含您已经拥有的任何代码,包括您尝试读取该值。
  • 是这样的
  • 您可以只读取文件并将其保存为字符串。这个网站上应该有足够的帖子来解释如何做到这一点。
  • 当您接受答案时,我们知道问题已得到您满意的回答。无需编辑标题。

标签: c# json http


【解决方案1】:

一种可能性是使用System.Net.WebClient 下载数据:(已过时,请参阅下面的编辑。)

// WebClient is outdated
string json;
using(var webClient = new WebClient())
{
   json = webClient.DownloadString("http://URL.com/filename.json");
}

下载字符串后,您可以使用Json.Net 之类的框架对其进行反序列化。因为它是一个简单的 JSON 文件,我们可以将其反序列化为字典。这样我们就不必为它创建一个显式的类:

var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);

现在我们可以像这样访问版本了:

var versionString = dict["CurrentVersion"];

编辑
就像 cmets 中所说的@CodeCaster:System.Net.WebClient 的用法已经过时。相反,应该使用System.Net.Http.HttpClient。下载 JSON 可能如下所示:

// HttpClient is intended to be instantiated once per application, rather than per-use.
private readonly HttpClient _httpClient = new HttpClient();

[...]

var json = _httpClient.GetStringAsync("http://URL.com/filename.json");

// Do something with JSON
猜你喜欢
  • 1970-01-01
  • 2019-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多