1
votes

Flutter: Comment obtenir la méthode de carte imbriquée json

Nouveau sur Flutte / Dart. Quelle pourrait être la cause de mes problèmes de mappage?

Launching lib\main.dart on Android SDK built for x86 in debug mode...
Initializing gradle...
Resolving dependencies...
Running Gradle task 'assembleDebug'...
Built build\app\outputs\apk\debug\app-debug.apk.
Flutter is taking longer than expected to report its views. Still trying...
I/OpenGLRenderer( 5371): Initialized EGL, version 1.4
D/OpenGLRenderer( 5371): Swap behavior 1
D/        ( 5371): HostConnection::get() New Host Connection established 0xdd5d9200, tid 5399
D/EGL_emulation( 5371): eglCreateContext: 0xde80f4c0: maj 2 min 0 rcv 2
D/EGL_emulation( 5371): eglMakeCurrent: 0xde80f4c0: ver 2 0 (tinfo 0xde37faf0)
D/        ( 5371): HostConnection::get() New Host Connection established 0xc8bb7680, tid 5390
D/EGL_emulation( 5371): eglCreateContext: 0xde37cc00: maj 2 min 0 rcv 2
D/EGL_emulation( 5371): eglMakeCurrent: 0xde37cc00: ver 2 0 (tinfo 0xde37f810)
I/Choreographer( 5371): Skipped 411 frames!  The application may be doing too much work on its main thread.
D/EGL_emulation( 5371): eglMakeCurrent: 0xde80f4c0: ver 2 0 (tinfo 0xde37faf0)
Syncing files to device Android SDK built for x86...
I/OpenGLRenderer( 5371): Davey! duration=8078ms; Flags=1, IntendedVsync=1110681936778, Vsync=1117531936504, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=1117546732479, AnimationStart=1117546825482, PerformTraversalsStart=1117546831170, DrawStart=1117600733845, SyncQueued=1117602574377, SyncStart=1117645210311, IssueDrawCommandsStart=1117645436189, SwapBuffers=1118338480166, FrameCompleted=1118803458523, DequeueBufferDuration=29600000, QueueBufferDuration=176000, 
D/EGL_emulation( 5371): eglMakeCurrent: 0xde37cc00: ver 2 0 (tinfo 0xde37f810)
I/flutter ( 5371): Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>'

Erreur

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

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

Future<List<Photo>> fetchPhotos(http.Client client) async {
  final response =
  await client.get('https://cloud.iexapis.com/stable/stock/market/batch?symbols=aapl,fb&types=quote&token=hidden');

  // Use the compute function to run parsePhotos in a separate isolate.
  return compute(parsePhotos, response.body);
}

// A function that converts a response body into a List<Photo>.
List<Photo> parsePhotos(String response) {
  List<Photo> Photos = new List<Photo>();
  List parsePhotos= json.decode(response.toString());
  for (int i = 0; i < parsePhotos.length; i++) {
    Photos.add(new Photo.fromJson(parsePhotos[i]));
  }
  return Photos;
}



class Photo {
  final String symbol;
  final String companyName;
  final String primaryExchange;
  final String calculationPrice;
  final int open;
  final int openTime;
  final double close;
  final int closeTime;
  final double high;
  final double low;
  final double latestPrice;
  final String latestSource;
  final String latestTime;
  final int latestUpdate;
  final int latestVolume;
  final dynamic iexRealtimePrice;
  final dynamic iexRealtimeSize;
  final dynamic iexLastUpdated;
  final double delayedPrice;
  final int delayedPriceTime;
  final double extendedPrice;
  final double extendedChange;
  final double extendedChangePercent;
  final int extendedPriceTime;
  final double previousClose;
  final int previousVolume;
  final int change;
  final double changePercent;
  final int volume;
  final dynamic iexMarketPercent;
  final dynamic iexVolume;
  final int avgTotalVolume;
  final dynamic iexBidPrice;
  final dynamic iexBidSize;
  final dynamic iexAskPrice;
  final dynamic iexAskSize;
  final int marketCap;
  final double peRatio;
  final double week52High;
  final int week52Low;
  final double ytdChange;
  final int lastTradeTime;
  final bool isUsMarketOpen;

  Photo({
    this.symbol,
    this.companyName,
    this.primaryExchange,
    this.calculationPrice,
    this.open,
    this.openTime,
    this.close,
    this.closeTime,
    this.high,
    this.low,
    this.latestPrice,
    this.latestSource,
    this.latestTime,
    this.latestUpdate,
    this.latestVolume,
    this.iexRealtimePrice,
    this.iexRealtimeSize,
    this.iexLastUpdated,
    this.delayedPrice,
    this.delayedPriceTime,
    this.extendedPrice,
    this.extendedChange,
    this.extendedChangePercent,
    this.extendedPriceTime,
    this.previousClose,
    this.previousVolume,
    this.change,
    this.changePercent,
    this.volume,
    this.iexMarketPercent,
    this.iexVolume,
    this.avgTotalVolume,
    this.iexBidPrice,
    this.iexBidSize,
    this.iexAskPrice,
    this.iexAskSize,
    this.marketCap,
    this.peRatio,
    this.week52High,
    this.week52Low,
    this.ytdChange,
    this.lastTradeTime,
    this.isUsMarketOpen,
  });

  factory Photo.fromJson(String str) => Photo.fromMap(json.decode(str));

  String toJson() => json.encode(toMap());

  factory Photo.fromMap(Map<String, dynamic> json) => Photo(
    symbol: json["symbol"],
    companyName: json["companyName"],
    primaryExchange: json["primaryExchange"],
    calculationPrice: json["calculationPrice"],
    open: json["open"],
    openTime: json["openTime"],
    close: json["close"].toDouble(),
    closeTime: json["closeTime"],
    high: json["high"].toDouble(),
    low: json["low"].toDouble(),
    latestPrice: json["latestPrice"].toDouble(),
    latestSource: json["latestSource"],
    latestTime: json["latestTime"],
    latestUpdate: json["latestUpdate"],
    latestVolume: json["latestVolume"],
    iexRealtimePrice: json["iexRealtimePrice"],
    iexRealtimeSize: json["iexRealtimeSize"],
    iexLastUpdated: json["iexLastUpdated"],
    delayedPrice: json["delayedPrice"].toDouble(),
    delayedPriceTime: json["delayedPriceTime"],
    extendedPrice: json["extendedPrice"].toDouble(),
    extendedChange: json["extendedChange"].toDouble(),
    extendedChangePercent: json["extendedChangePercent"].toDouble(),
    extendedPriceTime: json["extendedPriceTime"],
    previousClose: json["previousClose"].toDouble(),
    previousVolume: json["previousVolume"],
    change: json["change"],
    changePercent: json["changePercent"].toDouble(),
    volume: json["volume"],
    iexMarketPercent: json["iexMarketPercent"],
    iexVolume: json["iexVolume"],
    avgTotalVolume: json["avgTotalVolume"],
    iexBidPrice: json["iexBidPrice"],
    iexBidSize: json["iexBidSize"],
    iexAskPrice: json["iexAskPrice"],
    iexAskSize: json["iexAskSize"],
    marketCap: json["marketCap"],
    peRatio: json["peRatio"].toDouble(),
    week52High: json["week52High"].toDouble(),
    week52Low: json["week52Low"],
    ytdChange: json["ytdChange"].toDouble(),
    lastTradeTime: json["lastTradeTime"],
    isUsMarketOpen: json["isUSMarketOpen"],
  );

  Map<String, dynamic> toMap() => {
    "symbol": symbol,
    "companyName": companyName,
    "primaryExchange": primaryExchange,
    "calculationPrice": calculationPrice,
    "open": open,
    "openTime": openTime,
    "close": close,
    "closeTime": closeTime,
    "high": high,
    "low": low,
    "latestPrice": latestPrice,
    "latestSource": latestSource,
    "latestTime": latestTime,
    "latestUpdate": latestUpdate,
    "latestVolume": latestVolume,
    "iexRealtimePrice": iexRealtimePrice,
    "iexRealtimeSize": iexRealtimeSize,
    "iexLastUpdated": iexLastUpdated,
    "delayedPrice": delayedPrice,
    "delayedPriceTime": delayedPriceTime,
    "extendedPrice": extendedPrice,
    "extendedChange": extendedChange,
    "extendedChangePercent": extendedChangePercent,
    "extendedPriceTime": extendedPriceTime,
    "previousClose": previousClose,
    "previousVolume": previousVolume,
    "change": change,
    "changePercent": changePercent,
    "volume": volume,
    "iexMarketPercent": iexMarketPercent,
    "iexVolume": iexVolume,
    "avgTotalVolume": avgTotalVolume,
    "iexBidPrice": iexBidPrice,
    "iexBidSize": iexBidSize,
    "iexAskPrice": iexAskPrice,
    "iexAskSize": iexAskSize,
    "marketCap": marketCap,
    "peRatio": peRatio,
    "week52High": week52High,
    "week52Low": week52Low,
    "ytdChange": ytdChange,
    "lastTradeTime": lastTradeTime,
    "isUSMarketOpen": isUsMarketOpen,
  };
}


void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final appTitle = 'Isolate Demo';

    return MaterialApp(
      title: appTitle,
      home: MyHomePage(title: appTitle),
    );
  }
}

class MyHomePage extends StatelessWidget {
  final String title;

  MyHomePage({Key key, this.title}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: FutureBuilder<List<Photo>>(
        future: fetchPhotos(http.Client()),
        builder: (context, snapshot) {
          if (snapshot.hasError) print(snapshot.error);

          return snapshot.hasData
              ? PhotosList(photos: snapshot.data)
              : Center(child: CircularProgressIndicator());
        },
      ),
    );
  }
}

class PhotosList extends StatelessWidget {
  final List<Photo> photos;
//  final parsePhotos = json.decode(response.body).cast<Map<String, dynamic>>();
  PhotosList({Key key, this.photos}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GridView.builder(
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
      ),
      itemCount: photos.length,
      itemBuilder: (context, index) {
        return Image.network(photos[index].companyName);
      },
    );
  }
}

 entrez la description de l'image ici p >

Résultats Json:

{"AAPL": {"stats": {"week52change": 0,232986, "week52high": 255,93, "week52low": 142, "marketcap": 1136677331400, "employés": 137000, "day200MovingAvg": 199,29, "day50MovingAvg": 225.28, "float": 4436680630.59, "avg10Volume": 26482506.4, "avg30Volume": 26817874.5, "ttmEPS": 11.9342, "ttmDividendRate": 3, "companyName", "Apple, Inc. : 4443270000, "maxChangePercent": 252.2871, "year5ChangePercent": 1.3384, "year2ChangePercent": 0.5329, "year1ChangePercent": 0.1512, "ytdChangePercent": 0.6199, "month6ChangePercent": 0.2152, "month6ChangePercent": 0.2152, "mois , "day30ChangePercent": 0.1696, "day5ChangePercent": 0.0272, "nextDividendDate": "2019-11-07", "dividendYield": 0.011726995543741695, "nextEarningsDate": "2020-02-04", "exDividendDate": "2019- 11-07 "," peRatio ": 21.44," beta ": 1.534927573962706}," quote ": {" symbol ":" AAPL "," companyName ":" Apple, Inc. "," PrimaryExchange ":" NASDAQ ", "calculPrice": "close", "open": 249,5, "openTime": 1572615000544, "close": 255.82, "closeTime": 1572638400572, "high": 255.93, "low ": 249.16," latestPrice ": 255.82," latestSource ":" Close "," latestTime ":" 1 novembre 2019 "," latestUpdate ": 1572638400572," latestVolume ": 38139225," iexRealtimePrice ": null, p >

Capture d'écran Json

[Capture d'écran de json [2]

Trace de pile

{"AAPL": {"stats": {"week52change": 0,232986, "week52high": 255,93, "week52low": 142, "marketcap": 1136677331400, "employés": 137000, "day200MovingAvg": 199,29, "day50MovingAvg": 225.28, "float": 4436680630.59, "avg10Volume": 26482506.4, "avg30Volume": 26817874.5, "ttmEPS": 11.9342, "ttmDividendRate": 3, "companyName", "Apple, Inc. : 4443270000, "maxChangePercent": 252.2871, "year5ChangePercent": 1.3384, "year2ChangePercent": 0.5329, "year1ChangePercent": 0.1512, "ytdChangePercent": 0.6199, "month6ChangePercent": 0.2152, "month6ChangePercent": 0.2152, "mois , "day30ChangePercent": 0.1696, "day5ChangePercent": 0.0272, "nextDividendDate": "2019-11-07", "dividendYield": 0.011726995543741695, "nextEarningsDate": "2020-02-04", "exDividendDate": "2019- 11-07 "," peRatio ": 21.44," beta ": 1.534927573962706}," quote ": {" symbol ":" AAPL "," companyName ":" Apple, Inc. "," PrimaryExchange ":" NASDAQ ", "calculPrice": "close", "open": 249,5, "openTime": 1572615000544, "close": 255.82, "closeTime": 1572638400572, "high": 255.93, "low ": 249.16," latestPrice ": 255.82," latestSource ":" Close "," latestTime ":" 1 novembre 2019 "," latestUpdate ": 1572638400572," latestVolume ": 38139225," iexRealtimePrice ": null, p >

Screenshot

 entrez la description de l'image ici

Attendu: Exemple: https://flutter.dev/docs/cookbook/networking/background-parsing entrez la description de l'image ici


0 commentaires

4 Réponses :


0
votes

Essayez ceci:

List<Photo> parsePhotos(String response) {
  return List<Photo>.from(
    json.decode(response.body).map((x) => Photo.fromJson(x)));
}

Au fait, jsontodart est vraiment utile pour convertir json en objet ou objet en json


3 commentaires

J'ai utilisé cette conversion json auparavant sur la même application et mon code ne fonctionnait toujours pas. où exactement j'ajoute le code que vous avez posté?


Quelle serait la valeur de x map ((x) => Photo.fromJson (x)));


Je viens de modifier la réponse. il suffit de le mettre dans parsePhotos. x est la valeur de json après le décodage. Je pense que mon exemple fonctionnera si votre json est List mais semble être juste un objet Map, votre json n’a pas [] donc vous ne pouvez pas convertir en List



2
votes

La racine du JSON que vous avez associée en tant que "résultats Json" est une carte, mais vous essayez de l'attribuer à la variable List ici:

Photo.fromJson(jsonDecode('{"d":0.5,"nestedMaps":{"test":{"s":"a"},"test2":{"s":"a"}},"list":["a","b"]}'));

Assurez-vous que vous travaillez correctement avec votre structure de réponse. Accédez également au corps de la réponse, ne convertissez pas l'intégralité de l'objet de la réponse en chaîne:

flutter packages pub run build_runner build

Je recommande également fortement d'utiliser des générateurs de code pour la (dé) sérialisation JSON afin de faciliter la tu. json_serializable et build_runner vous aidera à le faire. Je vais vous montrer un exemple comment désérialiser un objet avec des cartes imbriquées:

import 'package:json_annotation/json_annotation.dart';

part 'photo.g.dart';

@JsonSerializable()
class Photo {
  final double d;
  final Map<String, Map> nestedMaps;
  final List<String> list;

  Photo(this.d, this.nestedMaps, this.list);

  factory Photo.fromJson(Map<String, dynamic> json) => _$PhotoFromJson(json);
  Map<String, dynamic> toJson() => _$PhotoToJson(this);
}

Définissez une classe et utilisez l'annotation JsonSerializable:

{"d":0.5,"nestedMaps":{"test":{"s":"a"},"test2":{"s":"a"}},"list":["a","b"]}


0 commentaires

1
votes

Démo de travail complète testée avec un vrai jeton, vous pouvez copier coller le code complet ci-dessous
Dans l'exemple de code, j'ai supprimé le jeton, vous devez le rajouter

la chaîne json dans la réponse réelle est " quote " et dans votre question est " stat code > "
Vous devez vérifier la chaîne de réponse avant la mise en page
quote actuellement utilisée est photos[index Often. >

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

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

Future<List<Photo>> fetchPhotos(http.Client client) async {
 final response =
  await client.get('https://cloud.iexapis.com/stable/stock/market/batch?symbols=aapl,fb&types=quote&token=xxx');
  /*String response = '''
 {"AAPL":
   {"stats":{"week52change":0.232986,"week52high":255.93,"week52low":142,"marketcap":1136677331400,"employees":137000,"day200MovingAvg":199.29,"day50MovingAvg":225.28,"float":4436680630.59,"avg10Volume":26482506.4,"avg30Volume":26817874.5,"ttmEPS":11.9342,"ttmDividendRate":3,"companyName":"Apple, Inc."
   }
   },
 "FB":
   {"stats":{"week52change":0.1,"week52high":255.93,"week52low":142,"marketcap":1136677331400,"employees":137000,"day200MovingAvg":199.29,"day50MovingAvg":225.28,"float":4436680630.59,"avg10Volume":26482506.4,"avg30Volume":26817874.5,"ttmEPS":11.9342,"ttmDividendRate":3,"companyName":"Apple, Inc."
   }
   }  
}
  ''';*/
  // Use the compute function to run parsePhotos in a separate isolate.
  return compute(parsePhotos, response.body);
}

// A function that converts a response body into a List<Photo>.
List<Photo> parsePhotos(String responseBody) {
  //final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();

  //return parsed.map<Photo>((json) => Photo.fromJson(json)).toList();

  dynamic Obj = json.decode(responseBody);
  print(Obj.length);
  List<Photo> photoList = [];
  Obj.forEach((k, v) => photoList.add(Photo(k, v)));

  return photoList;
}

class Photo {
  String symbol;
  dynamic data;

  Photo(this.symbol, this.data);
}

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final appTitle = 'Isolate Demo';

    return MaterialApp(
      title: appTitle,
      home: MyHomePage(title: appTitle),
    );
  }
}

class MyHomePage extends StatelessWidget {
  final String title;

  MyHomePage({Key key, this.title}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: FutureBuilder<List<Photo>>(
        future: fetchPhotos(http.Client()),
        builder: (context, snapshot) {
          if (snapshot.hasError) print(snapshot.error);

          return snapshot.hasData
              ? PhotosList(photos: snapshot.data)
              : Center(child: CircularProgressIndicator());
        },
      ),
    );
  }
}

class PhotosList extends StatelessWidget {
  final List<Photo> photos;

  PhotosList({Key key, this.photos}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GridView.builder(
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
      ),
      itemCount: photos.length,
      itemBuilder: (context, index) {
        return ListTile(
          leading: Icon(Icons.album),
          title: Text(photos[index].symbol),
          subtitle: Text( ' ${photos[index].data["quote"]["iexRealtimePrice"]}'),
        );
      },
    );
  }
}

code complet supprimez votre jeton

{"AAPL":{"quote":{"symbol":"AAPL","companyName":"Apple, Inc.","primaryExchange":"NASDAQ","calculationPrice":"close","open":265.69,"openTime":1574260200209,"close":263.19,"closeTime":1574283600212,"high":266.083,"low":260.4,"latestPrice":263.19,"latestSource":"Close","latestTime":"November 20, 2019","latestUpdate":1574283600212,"latestVolume":26015446,"iexRealtimePrice":262.83,"iexRealtimeSize":19,"iexLastUpdated":1574283604924,"delayedPrice":263.19,"delayedPriceTime":1574283600212,"extendedPrice":263.35,"extendedChange":0.16,"extendedChangePercent":0.00061,"extendedPriceTime":1574384397682,"previousClose":266.29,"previousVolume":19069597,"change":-3.1,"changePercent":-0.01164,"volume":26015446,"iexMarketPercent":0.015005278018297284,"iexVolume":390369,"avgTotalVolume":24440833,"iexBidPrice":0,"iexBidSize":0,"iexAskPrice":0,"iexAskSize":0,"marketCap":1169424231300,"peRatio":22.05,"week52High":268,"week52Low":142,"ytdChange":0.674594,"lastTradeTime":1574283604924,"isUSMarketOpen":false}},"FB":{"quote":{"symbol":"FB","companyName":"Facebook, Inc.","primaryExchange":"NASDAQ","calculationPrice":"close","open":198.58,"openTime":1574260200212,"close":197.51,"closeTime":1574283600333,"high":199.59,"low":195.43,"latestPrice":197.51,"latestSource":"Close","latestTime":"November 20, 2019","latestUpdate":1574283600333,"latestVolume":11999607,"iexRealtimePrice":197.5,"iexRealtimeSize":100,"iexLastUpdated":1574283599989,"delayedPrice":197.5,"delayedPriceTime":1574283599989,"extendedPrice":196.5,"extendedChange":-1.01,"extendedChangePercent":-0.00511,"extendedPriceTime":1574384390404,"previousClose":199.32,"previousVolume":19070291,"change":-1.81,"changePercent":-0.00908,"volume":11999607,"iexMarketPercent":0.020256580069663948,"iexVolume":243071,"avgTotalVolume":14362105,"iexBidPrice":0,"iexBidSize":0,"iexAskPrice":0,"iexAskSize":0,"marketCap":563391349700,"peRatio":31.36,"week52High":208.66,"week52Low":123.02,"ytdChange":0.459965,"lastTradeTime":1574283599989,"isUSMarketOpen":false}}}

démo

 entrez la description de l'image ici a>


12 commentaires

voulez-vous dire que vous copiez coller exécutez mon code complet et obtenez cette erreur?


pourriez-vous poster toute la chaîne json. Je peux le faire fonctionner.


Je n'ai pas de paramètre response.body. Votre réponse est une réponse http, j'utilise une réponse String pour simuler votre json renvoyé. tu dois changer cette partie


Copiez collez votre URL. et j'obtiens un symbole inconnu


vous avez typo marché. Je reçois des données maintenant. travaillera dessus.


tout a fonctionné. vous pouvez copier coller. et changez le jeton en jeton réel


J'ai mis à jour ma réponse. Tout a fonctionné. Faites-moi savoir si vous avez encore des problèmes. et n'oubliez pas de supprimer votre commentaire contenant votre token.


Comment pouvez-vous vous contacter pour référence future?


Vous pouvez publier une question et dans les commentaires, vous pouvez utiliser le symbole @ pour envoyer un ping à une personne. En fait, il y a beaucoup de gens qui peuvent vous aider.


Il semble que vous ne cliquez pas sur l'icône d'attribution de prime. Rencontrez-vous encore une autre question? Merci.


Oui. Merci beaucoup.


a ajouté un autre nouveau message de question :)



0
votes

En supposant que la structure JSON que vous téléchargez est fixe, vous pouvez spécifier le "chemin" de chaque propriété dans Photo.fromJson comme suit:

propr: json["prop"] as double,

à la place sur:

prop: json["prop"].toDouble(),

Veuillez exécuter l'exemple de code suivant et vous verrez que Photo.close et Photo.latestVolume sont maintenant correctement chargés à partir de votre JSON car j'ai spécifié le bon "chemin" dans Photo.fromJson:

import 'dart:convert';

void main() {
  var jsonStream = '{"AAPL":{"stats":{"companyName":"Apple, Inc.","sharesOutstanding":4443270000,"maxChangePercent":252.2871,"year5ChangePercent":1.3384,"year2ChangePercent":0.5329,"beta":1.534927573962706},"quote":{"symbol":"AAPL","companyName":"Apple, Inc.","primaryExchange":"NASDAQ","calculationPrice":"close","open":249.5,"openTime":1572615000544,"close":255.82,"closeTime":1572638400572,"high":255.93,"low":249.16,"latestPrice":255.82,"latestSource":"Close","latestTime":"November 1, 2019","latestUpdate":1572638400572,"latestVolume":38139225,"iexRealtimePrice":null}}}';

  var j = json.decode(jsonStream);
  print(j);
  print("");
  print("Latest Volume: ${j["AAPL"]["quote"]["latestVolume"]}");
  print("Close: ${j["AAPL"]["quote"]["close"]}");
  print("");

  var p = Photo.fromJson(j);

  print("Latest Volume: ${p.latestVolume}");
  print("Close: ${p.close}");
}

class Photo {
  final String symbol;
  final String companyName;
  final String primaryExchange;
  final String calculationPrice;
  final int open;
  final int openTime;
  final double close;
  final int closeTime;
  final double high;
  final double low;
  final double latestPrice;
  final String latestSource;
  final String latestTime;
  final int latestUpdate;
  final int latestVolume;
  final dynamic iexRealtimePrice;
  final dynamic iexRealtimeSize;
  final dynamic iexLastUpdated;
  final double delayedPrice;
  final int delayedPriceTime;
  final double extendedPrice;
  final double extendedChange;
  final double extendedChangePercent;
  final int extendedPriceTime;
  final double previousClose;
  final int previousVolume;
  final int change;
  final double changePercent;
  final int volume;
  final dynamic iexMarketPercent;
  final dynamic iexVolume;
  final int avgTotalVolume;
  final dynamic iexBidPrice;
  final dynamic iexBidSize;
  final dynamic iexAskPrice;
  final dynamic iexAskSize;
  final int marketCap;
  final double peRatio;
  final double week52High;
  final int week52Low;
  final double ytdChange;
  final int lastTradeTime;
  final bool isUsMarketOpen;

  Photo({
    this.symbol,
    this.companyName,
    this.primaryExchange,
    this.calculationPrice,
    this.open,
    this.openTime,
    this.close,
    this.closeTime,
    this.high,
    this.low,
    this.latestPrice,
    this.latestSource,
    this.latestTime,
    this.latestUpdate,
    this.latestVolume,
    this.iexRealtimePrice,
    this.iexRealtimeSize,
    this.iexLastUpdated,
    this.delayedPrice,
    this.delayedPriceTime,
    this.extendedPrice,
    this.extendedChange,
    this.extendedChangePercent,
    this.extendedPriceTime,
    this.previousClose,
    this.previousVolume,
    this.change,
    this.changePercent,
    this.volume,
    this.iexMarketPercent,
    this.iexVolume,
    this.avgTotalVolume,
    this.iexBidPrice,
    this.iexBidSize,
    this.iexAskPrice,
    this.iexAskSize,
    this.marketCap,
    this.peRatio,
    this.week52High,
    this.week52Low,
    this.ytdChange,
    this.lastTradeTime,
    this.isUsMarketOpen,
  });

  factory Photo.fromJson(Map<String, dynamic> json) => Photo(
    symbol: json["symbol"],
    companyName: json["companyName"],
    primaryExchange: json["primaryExchange"],
    calculationPrice: json["calculationPrice"],
    open: json["open"],
    openTime: json["openTime"],
    close: json["AAPL"]["quote"]["close"] as double, // Points to correct "path"
    closeTime: json["closeTime"],
    high: json["high"] as double,
    low: json["low"] as double,
    latestPrice: json["latestPrice"] as double,
    latestSource: json["latestSource"],
    latestTime: json["latestTime"],
    latestUpdate: json["latestUpdate"],
    latestVolume: json["AAPL"]["quote"]["latestVolume"], // Points to correct "path"
    iexRealtimePrice: json["iexRealtimePrice"],
    iexRealtimeSize: json["iexRealtimeSize"],
    iexLastUpdated: json["iexLastUpdated"],
    delayedPrice: json["delayedPrice"] as double,
    delayedPriceTime: json["delayedPriceTime"],
    extendedPrice: json["extendedPrice"] as double,
    extendedChange: json["extendedChange"] as double,
    extendedChangePercent: json["extendedChangePercent"] as double,
    extendedPriceTime: json["extendedPriceTime"],
    previousClose: json["previousClose"] as double,
    previousVolume: json["previousVolume"],
    change: json["change"],
    changePercent: json["changePercent"] as double,
    volume: json["volume"],
    iexMarketPercent: json["iexMarketPercent"],
    iexVolume: json["iexVolume"],
    avgTotalVolume: json["avgTotalVolume"],
    iexBidPrice: json["iexBidPrice"],
    iexBidSize: json["iexBidSize"],
    iexAskPrice: json["iexAskPrice"],
    iexAskSize: json["iexAskSize"],
    marketCap: json["marketCap"],
    peRatio: json["peRatio"] as double,
    week52High: json["week52High"] as double,
    week52Low: json["week52Low"],
    ytdChange: json["ytdChange"] as double,
    lastTradeTime: json["lastTradeTime"],
    isUsMarketOpen: json["isUSMarketOpen"],
  );
}

Vous pouvez exécuter le code dans DartPad à: https://dartpad.dartlang.org

Encore une chose: veuillez noter que j'ai changé votre code d'origine:

close: json["close"],

en:

close: json["AAPL"]["quote"]["close"],

C'est parce que .ToDouble () échouerait si le champ JSON est nul . Sauf si vous avez une raison particulière d'exiger des champs dynamiques , vous pouvez les déclarer directement comme double

J'espère que cela vous aidera :)

p>


0 commentaires