Home > Software engineering >  How to deserialize an Object from Map (DART)
How to deserialize an Object from Map (DART)

Time:06-09

how can I re-create objects from a serialized/deserialized map of objects?

import 'dart:convert';

class InternalTx {
  int a;
  bool b;

  InternalTx(this.a, this.b);

  factory InternalTx.fromJson(Map<String, dynamic> json) =>
      InternalTxFromJson(json);

  Map<String, dynamic> toJson() => InternalTxToJson(this);
}

InternalTx InternalTxFromJson(Map<String, dynamic> json) => InternalTx(
      json['a'] as int,
      json['b'] as bool,
    );

Map<String, dynamic> InternalTxToJson(InternalTx instance) => <String, dynamic>{
      'a': instance.a,
      'b': instance.b,
    };

main() {
  Map<String, InternalTx> m = {};
  for (int i=0; i<10; i  )
  {
    InternalTx itx = InternalTx(i, false);
    m["Hello: $i"] = itx;
  }
  
  String serM = jsonEncode(m);
  print(serM);
  
  ////SERILIZED OKAY
  
  Map<String, dynamic> n = jsonDecode(serM);
  InternalTx newItx = n["Hello: 0"];      <-- Problem here.
  print(newItx);
}

Output:

{"Hello: 0":{"a":0,"b":false},"Hello: 1":{"a":1,"b":false},"Hello: 2":{"a":2,"b":false},"Hello: 3":{"a":3,"b":false},"Hello: 4":{"a":4,"b":false},"Hello: 5":{"a":5,"b":false},"Hello: 6":{"a":6,"b":false},"Hello: 7":{"a":7,"b":false},"Hello: 8":{"a":8,"b":false},"Hello: 9":{"a":9,"b":false}}
Uncaught Error: TypeError: Instance of '_JsonMap': type '_JsonMap' is not a subtype of type 'InternalTx'

What is missing here to deserialize the map of objects correctly? Thanks!

CodePudding user response:

You need to actually call the InternalTx.fromJson constructor since this is not done automatically. So your last piece of code should be:

  ////SERILIZED OKAY
  Map<String, dynamic> n = jsonDecode(serM);
  InternalTx newItx = InternalTx.fromJson(n["Hello: 0"]);
  print(newItx); // Instance of 'InternalTx'
  • Related