【问题标题】:Flutter JSON not reading correctlyFlutter JSON 无法正确读取
【发布时间】:2018-06-01 22:00:01
【问题描述】:

这可能需要一段时间... 我一直在尝试让我的 Dart/Flutter 代码从 BlockChainTicker 返回数据(特别是我想查看 AUD 行中的所有内容)并将其留在调试控制台中。当我这样做时,我会从控制台返回此错误

E/flutter ( 8656): [ERROR:topaz/lib/tonic/logging/dart_error.cc(16)] Unhandled exception:
E/flutter ( 8656): type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List' where
E/flutter ( 8656):   _InternalLinkedHashMap is from dart:collection
E/flutter ( 8656):   String is from dart:core
E/flutter ( 8656):   List is from dart:core

我的代码可能看起来很陌生,但我只有大约一周的这门语言经验,所以感谢您耐心阅读本文。

import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;



class First extends StatefulWidget {
  @override
  HomePageState createState() => new HomePageState();
}

class HomePageState extends State<First> {

  List data;

  Future<String> getData() async {
    var response = await http.get(
      Uri.encodeFull("http://blockchain.info/ticker"),
      headers: {
        "Accept": "application/json"
      }
    );
    data = JSON.decode(response.body);
    print(data[1]["AUD"]);

    return "Success!";
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: new Center(
        child: new RaisedButton(
          child: new Text("Get data"),
          onPressed: getData,
        ),
      ),
    );
  }
}

【问题讨论】:

    标签: android ios json dart flutter


    【解决方案1】:

    您的 json 的顶层是一个地图(不是列表 - 在 json 中,列表括在括号中)

    {
      "USD" : {"15m" : 7492.85, "last" : 7492.85, "buy" : 7492.85, "sell" : 7492.85, "symbol" : "$"},
      "AUD" : {"15m" : 9899.28, "last" : 9899.28, "buy" : 9899.28, "sell" : 9899.28, "symbol" : "$"},
      "BRL" : {"15m" : 28214.31, "last" : 28214.31, "buy" : 28214.31, "sell" : 28214.31, "symbol" : "R$"},
    

    所以改变:

    print(data[1]["AUD"]);
    

    到

    print(data["AUD"]); // prints the whole AUD map
    print(data['AUD']['last']); // prints the AUD 'last' double
    
    String isoCode = 'AUD';
    print('$isoCode -> ${data[isoCode]}');
    

    【讨论】:

    • 非常感谢,一直在网上搜索修复,很高兴收到回复。 :)
    • 另外,Richard,当我使用此代码时,调试控制台中的字符串上没有显示 AUD,您能指导我使用什么代码吗?
    • 奇怪,它在一个小测试工具中对我有用。你能澄清一下你希望看到什么吗?没看到?
    • 这是我在控制台中看到的:{15m: 10112.61, last: 10112.61, buy: 10112.61, sell: 10112.61, symbol: $} 这就是我想看"AUD" : {15m: 10112.61, last: 10112.61, buy: 10112.61, sell: 10112.61, symbol: $} (真的就是想看看AUD被选中了,没有参考看看我是否选择了正确的线)。
    • 也许是这样?
    猜你喜欢
    • 1970-01-01
    • 2020-07-24
    • 2021-11-04
    • 1970-01-01
    • 1970-01-01
    • 2015-06-12
    • 1970-01-01
    • 2021-12-07
    • 2012-04-11
    相关资源
    最近更新 更多