简体   繁体   中英

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

How to convert the resulted json data into models, if data has string keyword name?

Json Data

{
    "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"
        },
}

I need to map this data with model. Please help me.

Have you already got a model that you need to deserialise? or you want to know what you need to make the model out of?

In the event you already have the model, there are plenty of options floating around which this would easily be marked a duplicate of.

However, if you're unsure of what sort of model you need, if you're using the Newtonsoft.JSON library, you can use the JsonProperty attribute like this:

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 ...

}

Excuse the syntax being a little off maybe, I wrote that in Notepad. Side note - That JSON is horrendously formatted, those are really bad field names.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM