如何在不创建类的情况下反序列化 JSON?



所以我正在尝试从这个 JSON 文件 json 文件中获取值

{ "全球报价":{ "01. 符号": "IBM", "02. 开盘": "125.8300", "03. 高": "126.2500", "04. 低": "123.4000", "05. 价格": "124.1500", "06. 卷": "3115104", "07. 最新交易日": "2020-06-17", "08. 昨收盘价": "125.1500", "09. 更改": "-1.0000", "10. 变化百分比": "-0.7990%" } }

我尝试在Visual Studio中使用特殊粘贴创建类,它给出了这样的结果:

public class Rootobject
{
public GlobalQuote GlobalQuote { get; set; }
}
public class GlobalQuote
{
public string _01symbol { get; set; }
public string _02open { get; set; }
public string _03high { get; set; }
public string _04low { get; set; }
public string _05price { get; set; }
public string _06volume { get; set; }
public string _07latesttradingday { get; set; }
public string _08previousclose { get; set; }
public string _09change { get; set; }
public string _10changepercent { get; set; }
}
WebClient webClient = new WebClient();
string result = webClient.DownloadString("URL Source");// the result is the json file
GlobalQuote m = JsonConvert.DeserializeObject<GlobalQuote>(result);

Console.WriteLine(m._01symbol);
Console.WriteLine(m._02open);
Console.WriteLine(m._03high);

它什么也没给我。 我认为问题是类中的属性与 JSON 文件不匹配。 JSON 文件中的属性包含空格的问题。 所以我正在寻找一种解决方案,可以在不使用类的情况下从 JSON 文件中获取值。谁能帮我,提前感谢。

所以最后我找到了解决问题的方法:

public class Rootobject
{
[JsonProperty(PropertyName = "Global Quote")]
public GlobalQuote GlobalQuote { get; set; }
}
public class GlobalQuote
{
[JsonProperty(PropertyName = "01. symbol")]
public string _01symbol { get; set; }
[JsonProperty(PropertyName = "02. open")]
public string _02open { get; set; }
[JsonProperty(PropertyName = "03. high")]
public string _03high { get; set; }
[JsonProperty(PropertyName = "04. low")]
public string _04low { get; set; }
[JsonProperty(PropertyName = "05. price")]
public string _05price { get; set; }
[JsonProperty(PropertyName = "06. volume")]
public string _06volume { get; set; }
[JsonProperty(PropertyName = "07. latest trading day")]
public string _07latesttradingday { get; set; }
[JsonProperty(PropertyName = "08. previous close")]
public string _08previousclose { get; set; }
[JsonProperty(PropertyName = "09. change")]
public string _09change { get; set; }
[JsonProperty(PropertyName = "10. change percent")]
public string _10changepercent { get; set; }
}
Rootobject oRootObject = new Rootobject();
oRootObject = JsonConvert.DeserializeObject<Rootobject>(result);
Console.Writeline(oRootObject.GlobalQuote._02open);

最新更新