在 Json API 调用中被 DateTime 对象名称卡住 [英] Stuck with DateTime Object name in Json API call

查看:49
本文介绍了在 Json API 调用中被 DateTime 对象名称卡住的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在调用一个 API,它给了我一个像

I am calling an API which is giving me a json response like

{
"symbol": "AAPL",
"stock_exchange_short": "NASDAQ",
"timezone_name": "America/New_York",
"intraday": {
    "2018-11-21 15:59:00": {
        "open": "177.24",
        "close": "176.77",
        "high": "177.25",
        "low": "176.77",
        "volume": "430073"
    },
    "2018-11-21 15:58:00": {
        "open": "177.23",
        "close": "177.23",
        "high": "177.25",
        "low": "177.12",
        "volume": "188425"
    },
    "2018-11-21 15:57:00": {
        "open": "177.18",
        "close": "177.21",
        "high": "177.24",
        "low": "177.11",
        "volume": "163151"
    },

现在我想访问所有数据,所以我需要创建一个对象,但是当我使用 Json2cSharp 转换器时,它给了我一个无效类型的对象名称.那么我应该制作哪种类型的对象,以便我可以定期访问所有数据.请帮忙.

Now I want to access all data so I need to create an object of this but when I am using Json2cSharp converter then it gives me an object name which is invalid type. So which type of object I should make so I can access all data regularly. Please help.

推荐答案

你可以这样使用:

public partial class Welcome
{
    [JsonProperty("symbol")]
    public string Symbol { get; set; }

    [JsonProperty("stock_exchange_short")]
    public string StockExchangeShort { get; set; }

    [JsonProperty("timezone_name")]
    public string TimezoneName { get; set; }

    [JsonProperty("intraday")]
    public Dictionary<string, Intraday> Intraday { get; set; }
}

public partial class Intraday
{
    [JsonProperty("open")]
    public string Open { get; set; }

    [JsonProperty("close")]
    public string Close { get; set; }

    [JsonProperty("high")]
    public string High { get; set; }

    [JsonProperty("low")]
    public string Low { get; set; }

    [JsonProperty("volume")]
    public long Volume { get; set; }
}

棘手的部分是 Intraday 属性,因为您必须使用字典才能正确获取所有值.

The tricky part is the Intraday property, because you have to use a dictionary to get all the values correctly.

我使用了 quicktype(现在 json2csharp 正在与之合作).如果你想自己玩玩这个工具,这里有一个代码链接:https://app.quicktype.io?share=DRgQz3PJVCLy4JR3JtGZ

I've used quicktype (which json2csharp is now joining forces with). If you want to play yourself a bit with the tool here's a link to the code: https://app.quicktype.io?share=DRgQz3PJVCLy4JR3JtGZ

如果您更改右侧菜单中的选项,则会有更多代码.您可以将 Output Features 设置为 Complete 并得到一个非常好的片段.包括用法.在这种情况下,类似于下面的内容就足以将 json 反序列化为您的自定义类.

There's a lot more code there if you change options in the right menu. You can set the Output Features to Complete and will get a really nice snippet. Including the usage. In that case, something like the below will be enough to get the json deserialized to your custom class.

var welcome = Welcome.FromJson(jsonString);

希望这会有所帮助!

这篇关于在 Json API 调用中被 DateTime 对象名称卡住的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆