首页 > 解决方案 > 在 Flutter 中将 JSON 解析为 Dart 对象

问题描述

我是 Flutter 新手,对复杂的 JSON 解析知之甚少。我查阅了几篇在线文章,但没有找到任何适合该案例的解决方案。我的 JSON 如下:

{
   "RIFUSD":[
      {
         "timestamp":"2021-02-13T16:00:00.000Z",
         "open":"0.3257370",
         "close":"0.3257370",
         "min":"0.3257370",
         "max":"0.3257370",
         "volume":"49",
         "volumeQuote":"15.9611130"
      },
      {
         "timestamp":"2021-02-13T12:00:00.000Z",
         "open":"0.3015120",
         "close":"0.3216128",
         "min":"0.3015120",
         "max":"0.3216768",
         "volume":"4079",
         "volumeQuote":"1298.0319504"
      }
   ],
   "BERRYUSD":[
      {
         "timestamp":"2021-02-13T04:00:00.000Z",
         "open":"0.00061800",
         "close":"0.00061780",
         "min":"0.00061000",
         "max":"0.00071783",
         "volume":"10460",
         "volumeQuote":"6.89477840"
      },
      {
         "timestamp":"2021-02-12T20:00:00.000Z",
         "open":"0.00060489",
         "close":"0.00061800",
         "min":"0.00048829",
         "max":"0.00061800",
         "volume":"466690",
         "volumeQuote":"228.12405820"
      }
   ]
}

还有我的蜡烛类来保持时间戳、打开、关闭、最小值、最大值、体积和体积引用:

class Candle {
  Candle({
    this.timestamp,
    this.open,
    this.close,
    this.min,
    this.max,
    this.volume,
    this.volumeQuote,
  });

  final DateTime timestamp;
  final String open;
  final String close;
  final String min;
  final String max;
  final String volume;
  final String volumeQuote;

  factory Candle.fromRawJson(String str) => Candle.fromJson(json.decode(str));

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

  factory Candle.fromJson(Map<String, dynamic> json) => Candle(
        timestamp: json["timestamp"] == null
            ? null
            : DateTime.parse(json["timestamp"]),
        open: json["open"] == null ? null : json["open"],
        close: json["close"] == null ? null : json["close"],
        min: json["min"] == null ? null : json["min"],
        max: json["max"] == null ? null : json["max"],
        volume: json["volume"] == null ? null : json["volume"],
        volumeQuote: json["volumeQuote"] == null ? null : json["volumeQuote"],
      );

  Map<String, dynamic> toJson() => {
        "timestamp": timestamp == null ? null : timestamp.toIso8601String(),
        "open": open == null ? null : open,
        "close": close == null ? null : close,
        "min": min == null ? null : min,
        "max": max == null ? null : max,
        "volume": volume == null ? null : volume,
        "volumeQuote": volumeQuote == null ? null : volumeQuote,
      };
 }

我想将此 JSON 解析为:

class CandleList {
  CandleList({
    this.candleList,
    this.symbol,
  });

  final List<Candle> candleList;
  final Sym symbol;

  factory CandleList.fromRawJson(String str) =>
      CandleList.fromJson(json.decode(str));

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

  factory CandleList.fromJson(Map<String, dynamic> json) => CandleList(
        candleList: json["candleList"] == null
            ? null
            : List<Candle>.from(
                json["candleList"].map((x) => Candle.fromJson(x))),
        symbol: json["symbol"] == null ? null : Sym.fromJson(json["symbol"]),
      );

  Map<String, dynamic> toJson() => {
        "candleList": candleList == null
            ? null
            : List<dynamic>.from(candleList.map((x) => x.toJson())),
        "symbol": symbol == null ? null : symbol.toJson(),
      };

  @override
  String toString() {
    return '${symbol.id} > ${candleList.length} Candles';
  }
}

使用 List 和 "RIFUSD","BERRYUSD" 作为CandleList类的 symbol.id。

标签: jsonflutterparsingdart

解决方案


首先,在 Flutter 中安装 HTTP 包,然后像下面的代码一样导入 HTTP 包:

import 'package:http/http.dart' as HTTP;

然后你必须创建一个地图或一个列表:

  Map<int, FavoriteModel> _favoites = {};

  Map<int, FavoriteModel> get favoitesItem {
    return _favoites;
  }

然后你可以获取你的数据:

Future<void> getFavoriteList({
  @required int userId,
}) async {
  try {
    final response = await http.get("your url");
    final extractedData = json.decode(response.body);
    if (extractedData == null) {
      return;
    }
    final Map<int, YourModel> loadedProducts = {};

    print("Mahdi: favorite food ${extractedData['RIFUSD']}");

    final lastExtract = extractedData['RIFUSD'];

    lastExtract.forEach((prodData) {
      loadedProducts.putIfAbsent(
        prodData['timestamp'],
            () => YourModel(
          timestamp: prodData['timestamp'],
          open: prodData['open'],
        ),
      );
    });

    _favoites = loadedProducts;
    print("Mahdi ${_favoites.length}");
  } catch (error) {
    print("Mahdi E: $error");
    throw (error);
  }
}

我希望这对你有用


推荐阅读