我如何反序列化此json?它使用以下代码给出所有空值

时间:2018-11-20 04:30:26

标签: c# json

{
"Global Quote": {
    "01. symbol": "MSFT",
    "02. latest trading day": "2018-11-19",
    "03. previous close": "108.2900"}
}

这是我正在使用的代码:

using (var reader = new StreamReader(response.GetResponseStream()))
{
    JavaScriptSerializer js = new JavaScriptSerializer();
    var objText = reader.ReadToEnd();
    //This line is not working.
    Stock stock = (Stock)js.Deserialize(objText, typeof(Stock));
    return Ok(stock);
}

库存型号如下:

public class Stock
{
    public string symbol { get; set; }
    public string latesttradingday { get; set; }
    public string previousclose { get; set; } 
}

我在股票的所有字段中得到的都是Null。我在这里想念的是什么?我是JSON的新手。

1 个答案:

答案 0 :(得分:3)

使用JsonProperty

public class GlobalQuote
{
   [JsonProperty("Global Quote")]
   public Stock Stock { get; set; } 
}
public class Stock
{
   [JsonProperty("01. symbol")]
   public string symbol { get; set; }
   [JsonProperty("02. latest trading day")]
   public string latesttradingday { get; set; }
   [JsonProperty("03. previous close")]
   public string previousclose { get; set; } 
}
private static async Task Main(string[] args)
{
   string test = @"{
             ""Global Quote"": {
             ""01. symbol"": ""MSFT"",
             ""02. latest trading day"": ""2018-11-19"",
             ""03. previous close"": ""108.2900""}
         }";

   var result = JsonConvert.DeserializeObject<GlobalQuote>(test);

}

Full Demo Here


其他资源

JsonProperty Class

  

将JSON属性映射到.NET成员或构造函数参数。