【问题标题】:How would I access this JSON data in Dart for a flutter project?我将如何在 Dart 中为颤振项目访问此 JSON 数据?
【发布时间】:2020-07-07 17:42:38
【问题描述】:

这是 JSON 数据,我正在尝试使用此代码访问日期和开放值,但出现错误。正确的语法是什么?

factory Stock.fromJson(Map<String, dynamic> json) { // parse the json into data we can use
    return Stock(
      date: json['Time Series (Daily)[0]'],
      open: json['Time Series (Daily[0].open'],
      high: json['Time Series (Daily[0].high'],
      low: json['Time Series (Daily[0].low'],
      close: json['Time Series (Daily[0].close'],
      volume: json['Time Series (Daily[0].volume']
    );
  }
{
    "Meta Data": {
        "1. Information": "Daily Prices (open, high, low, close) and Volumes",
        "2. Symbol": "MSFT",
        "3. Last Refreshed": "2020-03-26",
        "4. Output Size": "Compact",
        "5. Time Zone": "US/Eastern"
    },
    "Time Series (Daily)": {
        "2020-03-26": {
            "1. open": "148.4000",
            "2. high": "156.6600",
            "3. low": "148.3700",
            "4. close": "155.8800",
            "5. volume": "64143669"
        }
}

【问题讨论】:

    标签: json api flutter dart


    【解决方案1】:

    要获取 json 对象或 json 数据的值,您需要传递属性名称并操作 json 对象

    factory Stock.fromJson(Map<String, dynamic> json) { // parse the json into data we can use
    return Stock(
      date: json['Time Series (Daily)']['2020-03-26'],
      open: json['Time Series (Daily)']['2020-03-26']['1. open'],
      ...
    );
    

    }

    您还可以使用此工具将您的 json 转换为 dart 对象:https://javiercbk.github.io/json_to_dart/

    【讨论】:

    • 谢谢!如果我不知道日期怎么办,当我尝试 json['Time Series (Daily)'][0]['1. open'] 来获取第一个日期,它返回 null。
    • 因为它不是一个列表。它是 的映射。您必须转换为这样的列表: json['Time Series (Daily)'].values.toList()[0]['1.打开']
    • 哇,非常感谢您提供的所有帮助。将来,您认为在堆栈溢出之前我可以检查一个更好的来源吗?我在 YouTube 或官方文档或搜索堆栈溢出时找不到你帮助我的这部分。
    • Stackoverflow 是寻求帮助的好地方。不过Flutter和json序列化的官方文档说的很清楚flutter.dev/docs/development/data-and-backend/json
    • 是的,我认为我的困惑源于官方文档似乎没有嵌套 JSON 的示例,而且我没有意识到我必须转换为列表形式。只是想改进,所以我打赌我不会再犯这个错误了。感谢大家的帮助
    猜你喜欢
    • 2021-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-31
    • 2019-07-27
    • 2020-05-09
    相关资源
    最近更新 更多