Ad

JSON ObjectMapper In Flutter

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 d?prettify?-->
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';
Ad

Answer

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

Ad
source: stackoverflow.com
Ad