Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
373 views
in Technique[技术] by (71.8m points)

android - Flutter JSON not reading correctly

this might take a while... I've been trying to get my Dart/Flutter code to return data from BlockChainTicker (Specifically I would like to see everything from the AUD line) and leave this in the Debug Console. When I do so, I get this error back from the Console

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

My code might seem amature but I only have about a weeks experience in this language, so thanks for any patience you might take in reading over this.

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,
        ),
      ),
    );
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The top level of your json is a map (not a list - in json, lists are enclosed in brackets)

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

So change:

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

to

print(data["AUD"]); // prints the whole AUD map
print(data['AUD']['last']); // prints the AUD 'last' double

String isoCode = 'AUD';
print('$isoCode -> ${data[isoCode]}');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...