Extracting an object from JSON in a 'parent' object's .fromJson method

61 views Asked by At

I want to store a ColorSwatch in json, and extract it in an object's .fromJson method.

I've tried storing it in JSON as:

"colorSwatch": "ColorSwatch(0xFFFFB7DE, { 'highlight': Color(0xFFFFB7DE), 'splash': Color(0xFFF94CBF) })"

Then extracting it with:

colorSwatch = jsonMap['colorSwatch'],

It didn't work. I tried changing the JSON to:

"colorSwatch": "0xFFFFB7DE, { 'highlight': Color(0xFFFFB7DE), 'splash': Color(0xFFF94CBF) }"

Then modifying the object's .fromJson method to:

colorSwatch = ColorSwatch(jsonMap['colorSwatch']),

It didn't work. I then tried:

colorSwatch = jsonMap['colorSwatch'] as ColorSwatch,

Didn't work.

I then tried saving the highlight and splash colours in json separately and extracting with

highlight = jsonMap['highlight'] as int,
splash = jsonMap['splash'] as int,
colorSwatch = new ColorSwatch(0xFFFFD28E, {'highlight': Color(highlight), 'splash': Color(splash)}),

But aparently I'm only allowed to do operations on static variables in an object's fromJson method.

So I'm stuck.

I want the ColorSwatch object attached to the Riddle object, so all the properties associated with a Riddle are in one place and don't need to be assembled elsewhere when needed.

  • It doesn't seem possible to build an Object, here ColorSwatch, inside another objects .fromJson method, is this correct?
  • So that means I have to extract the entire object in a single line of code, how do I do this?
1

There are 1 answers

1
Ali Qanbari On BEST ANSWER

Json doesn't support hexadecimals so you need to write them as a string and convert them using int.tryparse:

  var hexadecimalString = 'ff542144';
  var decimalInteger = int.tryParse(hexadecimalString, radix: 16);

for your ColorSwatch you need a helper class like this:

class ColorSwatch {
  final Color swatch;
  final Color splash;
  final Color highlight;

  ColorSwatch(this.swatch, this.splash, this.highlight);

  factory ColorSwatch.fromJson(Map<String, dynamic> json) {
    return ColorSwatch(
      Color(int.tryParse(json['colorSwatch'], radix: 16)),
      Color(int.tryParse(json['highlight'], radix: 16)),
      Color(int.tryParse(json['splash'], radix: 16)),
    );
  }

  String toJson() {
    return jsonEncode({
      'colorSwatch': swatch.value.toRadixString(16),
      'highlight': highlight.value.toRadixString(16),
      'splash': splash.value.toRadixString(16),
    });
  }
}