0

I'd like to have objects serialized/deserialized from JSON in Flutter. I know I can use JsonDecoder from json.dart which gives me string-key based LinkedHashMap but I'm more interested in ObjectMapper approach so that I'm able to get typed response from deserialization.

I tried redstone mapper (link) and exportable library (link) with Flutter - both of which I'm not able to compile properly. I believe the problem is connected with the reflection library from Dart.

How can I achieve a working Object-Json Mapper using Flutter?

Sample code:

class A {

  @Field()
  String b;
}

import 'package:redstone_mapper/mapper.dart';
import 'package:redstone_mapper/mapper_factory.dart';

bootstrapMapper();
var desObj = decodeJson(jsonString, A);

Error:

Starting device daemon...
Running lib/main.dart on Nexus 5X...
Dart snapshot generator failed with exit code 254
Errors encountered while loading: 'dart:mirrors': error: line 1 pos 1: unexpected token 'Unhandled'

or this one:

Error detected in application source code:
error: Failed to load main script:
'package:redstone_mapper/mapper_factory.dart': error: line 4 pos 1: import of dart:mirrors with --enable-mirrors=false
import 'dart:mirrors';

2 Answers2

5

The problem with the libraries you tried is that they use dart:mirrors, which is not supported on Flutter.

You should try a library which uses codegen instead, for instance built_value: https://github.com/google/built_value.dart

Harry Terkelsen
  • 2,554
  • 13
  • 11
0

As @HarryTerkelsen suggested there is built_value library from Google.

Serialization example can be found here. The downside is that built_value uses generated *.g.dart classes to create serializers so this library is not a simple "import & run" thing.

There is a sample project which showcases collection serialization. Collection and the generated serializer.

In short - you need to run this to generate your serializers.

EDIT:

In the end I ended up writing simple serialization from scratch:

import 'dart:convert';

class ItemDescription {
  String tag;

  String name;

  static ItemDescription deserialize(String str) {
    JsonDecoder decoder = new JsonDecoder();
    var deserializedMap = decoder.convert(str);
    return deserialize(deserializedMap);
  }

  static ItemDescription deserializeMap(Map map) {
      ItemDescription description = new ItemDescription();
      description.name = map["name"];
      description.tag = map["symbol"];
      return description;
  }
}