Parse JSON to Dart Object in Flutter

386

Solution 1

First of all, install the HTTP package in Flutter, and after that import HTTP package like the below code:

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

And then you must create a map or a list:

  Map<int, FavoriteModel> _favoites = {};

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

And then you can fetch your data:

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);
  }
}

I hope this works for you

Solution 2

data/raw_data_1.dart

const rawData = '''
{
   "RIFUSD":[
      {
   ....
      }
   ]
}
''';

main.dart

import 'dart:convert';

import 'data/raw_data_1.dart';


class NetService {
  static Future<Map<String, Object>> fetchData() {
    return Future.delayed(Duration(seconds: 2), () => rawData)
      .then((response) => jsonDecode(response));
  }
}

main(List<String> args) async {
  var data = await NetService.fetchData();
  var globalData = GlobalData.fromJson(data);
  print(globalData.data[0].id);
  print(globalData.data[0].candles[0].timestamp_UTC.toLocal().toString());
  print(globalData.data[0].candles[0].open.toString());
  print(globalData.data[0].candles[0].close.toString());
  print(globalData.data[0].candles[0].min.toString());
  print(globalData.data[0].candles[0].max.toString());
  print(globalData.data[0].candles[0].volume.toString());
  print(globalData.data[0].candles[0].volumeQuote.toString());
}

class Candle {
  DateTime timestamp_UTC;
  double open, close, min, max, volumeQuote;
  int volume;

  Candle.fromJson(Map<String, Object> jdata) {
    timestamp_UTC = DateTime.tryParse(jdata['timestamp']);
    open = double.tryParse(jdata['open']);
    close = double.tryParse(jdata['close']);
    min = double.tryParse(jdata['min']);
    max = double.tryParse(jdata['max']);
    volume = int.tryParse(jdata['volume']);
    volumeQuote = double.tryParse(jdata['volumeQuote']);
  }
}

class EntryOA {
  String id;
  List<Candle> candles;

  EntryOA.fromJson(MapEntry<String, Object> jdata) {
    this.id = jdata.key;
    var list = jdata.value as List<Object>;
    this.candles = List<Candle>.generate(list.length, (i) => Candle.fromJson(list[i] as Map<String, Object>));
  }
}

class GlobalData {
  List<EntryOA> data;
  
  GlobalData.fromJson(Map<String, Object> jdata) {
    data = jdata.entries.map((me) => EntryOA.fromJson(me)).toList();
  }
}

Result:

RIFUSD
2021-02-13 11:00:00.000
0.325737
0.325737
0.325737
0.325737
49
15.961113
Share:
386
Tofiq Samali
Author by

Tofiq Samali

Updated on December 27, 2022

Comments

  • Tofiq Samali
    Tofiq Samali over 1 year

    I'm new to Flutter and doesn't know much about complex JSON parsing. I've consulted few online articles but didn't find any suitable solution for the case. My JSON is as follows:

    {
       "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"
          }
       ]
    }
    

    And my Candle Class to keep timestamp, open, close, min, max, volume and volumeQuote:

    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,
          };
     }
    

    I want to parse this JSON into this:

    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';
      }
    }
    

    With List and "RIFUSD","BERRYUSD" as symbol.id of CandleList class.

    • Abbas Jafari
      Abbas Jafari about 3 years
      Hey, my friend did you get your answer?
    • Abbas Jafari
      Abbas Jafari about 3 years
      Did you get your answer?