簡體   English   中英

如何動態反序列化 C# 中 API 的 json 結果?

[英]How to dynamically deserialize the json result from API in C#?

如果數據具有字符串關鍵字名稱,如何將生成的 json 數據轉換為模型?

Json 數據

{
    "Meta Data": {
        "1. Information": "Intraday (5min) open, high, low, close prices and volume",
        "2. Symbol": "IBM",
        "3. Last Refreshed": "2020-06-30 12:50:00",
        "4. Interval": "5min",
        "5. Output Size": "Compact",
        "6. Time Zone": "US/Eastern"
    },
    "Time Series (5min)": {
        "2020-06-30 12:50:00": {
            "1. open": "119.7600",
            "2. high": "119.7600",
            "3. low": "119.5300",
            "4. close": "119.6300",
            "5. volume": "22938"
        },
        "2020-06-30 12:45:00": {
            "1. open": "120.0500",
            "2. high": "120.0600",
            "3. low": "119.7400",
            "4. close": "119.7900",
            "5. volume": "19170"
        },
}

我需要 map 這個數據和 model。 請幫我。

您是否已經擁有需要反序列化的 model? 或者您想知道制作 model 需要什么?

如果您已經擁有 model,則有很多選項浮動,很容易被標記為重復。

但是,如果您不確定需要哪種 model,如果您使用的是 Newtonsoft.JSON 庫,則可以使用 JsonProperty 屬性,如下所示:

public class DataType
{
    [JsonProperty("Meta Data")]
    public MetaDataType MetaData;

    [JsonProperty("Time Series (5min)")]
    public Dictionary<DateTime, TimeSeriesType> TimeSeries;

}
public class MetaDataType{

    [JsonProperty("1. Information")]
    public string Information;

    [JsonProperty("2. Symbol")]
    public string Symbol;

    ... etc ...

}
public class TimeSeriesType> {

    [JsonProperty("1. open")]
    public string Open;

    [JsonProperty("2. high")]
    public string High;

    ... etc ...

}

對不起,語法可能有點不對勁,我是在記事本中寫的。 旁注 - JSON 的格式非常糟糕,這些字段名稱非常糟糕。

暫無
暫無

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

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