2

I'm developing a game in Dart, and I want to migrate the drawing to PIXI.js. Basically one approach that occurred to me is to convert the game state into a JSON object, and pass this JSON object to an external JS method, which would then create the PIXI containers.

How do I make a JSON object and how do I pass it to an external JavaScript function?

Fernando Tiberti
  • 1,272
  • 2
  • 10
  • 18

2 Answers2

3
import 'dart:convert';

...

var json = JSON.encode(data);
...
var data = JSON.decode(json);

You probably want to use https://pub.dartlang.org/packages/js for dart-js-interop.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
3

JSON.encode and JSON.decode are that, what you are looking for, but they are work good with primitive types (be careful, for example DateTime - is not primitive) and collections of primitive types. So if you want to do it for object, you should convert it to map/from map. Conversion to map can be called automatically when object is passed to JSON.encode, if this object has method Map toJson(), conversion from map should be done explicitly (for example, with constructor with Map parameter).

Also, that can be useful: I prefer to avoid implicit toJson call, cause when it throws exception, you will not see its message and call stack in this case.

Useful links and some info about this can be found in this question.

Community
  • 1
  • 1
Adamovskiy
  • 1,376
  • 1
  • 12
  • 42