gpt4 book ai didi

c# - 在 C# 中解析 JSON 返回空值

转载 作者:行者123 更新时间:2023-11-30 23:29:52 26 4
gpt4 key购买 nike

我正在尝试在 C# 中解析 Json。 (我是 Json 初学者)

WebRequest webRequest = WebRequest.Create(url);
var httpWebRequest = (HttpWebRequest)webRequest;
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

String responseText = "";
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
responseText = streamReader.ReadToEnd();
}

//

这是响应文本中的输出:

{
"disclaimer": "Exchange rates provided for informational purposes only and do not constitute financial advice of any kind. Although every attempt is made to ensure quality, no guarantees are made of accuracy, validity, availability, or fitness for any purpose. All usage subject to acceptance of Terms: https://openexchangerates.org/terms/",
"license": "Data sourced from various providers; resale prohibited; no warranties given of any kind. All usage subject to License Agreement: https://openexchangerates.org/license/",
"timestamp": 1454497211,
"base": "EUR",
"rates": {
"INR": 74.42686146,
"USD": 1.0929332
}
}

从Json获取base

var obj = JObject.Parse(responseText);
String bcur = (string)obj["base"];
Console.WriteLine("base :"bcur.ToString());


Output : base :EUR

类似于获取 INR 的汇率,我写了

var obj = JObject.Parse(responseText);
String rte= (string)obj["INR"];
Console.WriteLine("rate:"rte);

it gives me null.

谁能告诉我我的代码有什么问题。或者更好的方法来获取货币的基数和汇率。

最佳答案

INR 不在基础对象中,因此您要在不存在的地方查找 INR 属性。您必须分两步进行才能访问 .修改上面的代码,它看起来像这样:

var obj = JObject.Parse(responseText);
JObject rates = (JObject)obj["rates"];
string rte = (string)rates["INR"];
Console.WriteLine("rate:" + rte);

关于c# - 在 C# 中解析 JSON 返回空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35178531/

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