Tofiq Samali
Tofiq Samali

Reputation: 329

Parse JSON to Dart Object in Flutter

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.

Upvotes: 1

Views: 502

Answers (3)

Kamal Bunkar
Kamal Bunkar

Reputation: 1452

You don't need to write dart file manually. You can use Online tool like Convert JSON response into Dart. I try it and the below is Dart class for your JSON response.

class Model_Candle {
  List<RIFUSD> rIFUSD;
  List<BERRYUSD> bERRYUSD;

  Model_Candle({this.rIFUSD, this.bERRYUSD});

  Model_Candle.fromJson(Map<String, dynamic> json) {
    if (json['RIFUSD'] != null) {
      rIFUSD = new List<RIFUSD>();
      json['RIFUSD'].forEach((v) {
        rIFUSD.add(new RIFUSD.fromJson(v));
      });
    }
    if (json['BERRYUSD'] != null) {
      bERRYUSD = new List<BERRYUSD>();
      json['BERRYUSD'].forEach((v) {
        bERRYUSD.add(new BERRYUSD.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.rIFUSD != null) {
      data['RIFUSD'] = this.rIFUSD.map((v) => v.toJson()).toList();
    }
    if (this.bERRYUSD != null) {
      data['BERRYUSD'] = this.bERRYUSD.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class RIFUSD {
  String timestamp;
  String open;
  String close;
  String min;
  String max;
  String volume;
  String volumeQuote;

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

  RIFUSD.fromJson(Map<String, dynamic> json) {
    timestamp = json['timestamp'];
    open = json['open'];
    close = json['close'];
    min = json['min'];
    max = json['max'];
    volume = json['volume'];
    volumeQuote = json['volumeQuote'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['timestamp'] = this.timestamp;
    data['open'] = this.open;
    data['close'] = this.close;
    data['min'] = this.min;
    data['max'] = this.max;
    data['volume'] = this.volume;
    data['volumeQuote'] = this.volumeQuote;
    return data;
  }
}

Now to access the value of RIFUSD you can write code like below

 final Map<String, dynamic> parsed = await wrapper.get_CategoryFull(catid);
final model = get_model_category.fromJson(parsed);
if (model.RIFUSD.length > 0) {
      for (int i = 0; i < model.RIFUSD.length; i++) {
        print( "timespamt "+ model.RIFUSD[i].timestamp.tostring() );
      }

    } 

Upvotes: 0

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

Upvotes: 1

Abbas Jafari
Abbas Jafari

Reputation: 1642

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

Upvotes: 1

Related Questions