简体   繁体   English

如何动态反序列化 C# 中 API 的 json 结果?

[英]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 数据转换为模型?

Json Data 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"
        },
}

I need to map this data with model.我需要 map 这个数据和 model。 Please help me.请帮我。

Have you already got a model that you need to deserialise?您是否已经拥有需要反序列化的 model? or you want to know what you need to make the model out of?或者您想知道制作 model 需要什么?

In the event you already have the model, there are plenty of options floating around which this would easily be marked a duplicate of.如果您已经拥有 model,则有很多选项浮动,很容易被标记为重复。

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:但是,如果您不确定需要哪种 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 ...

}

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.旁注 - JSON 的格式非常糟糕,这些字段名称非常糟糕。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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