簡體   English   中英

如何反序列化包含列表和字典(或鍵值)屬性對象的json字符串

[英]How can I deserialize a json string contianing a list and dictionary (or keyvalue) property objects

我想通過解析包含嵌入式contianer對象的Json字符串來創建C#對象。 請參見代碼段中的StockHistory。

我嘗試通過編譯器允許的多種方式定義父對象。 就像使用“字典”一樣在列表中包裝和不包裝“ KeyValue屬性”一樣,也嘗試使用單引號或雙引號來定義字符串。 大多數Stackoverflow清單都將列表或詞典顯示為父對象(contianer)。 但是我的容器是嵌入式的。

但是,如果需要自定義轉換器,則不確定如何編寫。 一個代碼片段會很棒。 我無法更改Json…它來自第三方服務器。

當我使用Visual Studio 2017 JSON Visualizer檢查json字符串時(通過突出顯示變量並單擊放大草),一切看起來都很好並且與預期的一樣。

using Newtonsoft.Json; // I'm using NuGet vs: 12.0.0.0
using System;
using System.Collections.Generic;

namespace ConsoleApp1
{
    class Program
    {
        public class StockHistory
        {
            public List<string> Meta_Data { get; set; }
            public Dictionary<string, LHOCV> Lhocv { get; set; }
        }

        public class LHOCV
        {
            public float Low { get; set; }
            public float High { get; set; }
            public float Open { get; set; }
            public float Close { get; set; }
            public double Volume { get; set; }
        }

        static void Main(string[] args)
        {
            string json =
 @"{
    'Meta Data': {
        '1. Information': 'Intraday (5min) ...',
        '2. Symbol': 'MSFT',
        '3. Last Refreshed': '2019-01-22 16:00:00',
        '4. Interval': '5min',
        '5. Output Size': 'Full size',
        '6. Time Zone': 'US/Eastern'
    },
    'Time Series (5min)': {
        '2019-01-22 16:00:00': {
            '1. open': '105.2200',
            '2. high': '105.8700',
            '3. low': '105.1000',
            '4. close': '105.8200',
            '5. volume': '1619877'
        },
        '2019-01-22 15:50:00': {
            '1. open': '105.4200',
            '2. high': '105.4800',
            '3. low': '105.2600',
            '4. close': '105.3000',
            '5. volume': '452625'
        }
    }
}";

StockHistory a = JsonConvert.DeserializeObject<StockHistory>(json);
// I can not get a value assigned to "a"... both container objects,
// Meta_Data and Lhocv, are rendered null.

//Console.WriteLine(a.Lhocv["2019-01-22 16:00:00"].High);
        }

    }
}

我希望c#變量“ a”(StockHistory)包含已解析的JSON密鑰和JSON字段“元數據”和“時間序列(5分鍾)”的數據。

我得到的是容器的空值。

這可能使您接近:

public class StockHistory
{
    [JsonProperty("Meta Data")]
    public Dictionary<string, string> Meta_Data { get; set; }
    [JsonProperty("Time Series (5min)")]
    public Dictionary<string, LHOCV> Lhocv { get; set; }
}

public class LHOCV
{
    [JsonProperty("3. low")]
    public float Low { get; set; }
    [JsonProperty("2. high")]
    public float High { get; set; }
    [JsonProperty("1. open")]
    public float Open { get; set; }
    [JsonProperty("4. close")]
    public float Close { get; set; }
    [JsonProperty("5. volume")]
    public double Volume { get; set; }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM