Skip to content

JSON serialization

This is how a protocol in Dart becomes the protocol.json the app and the Portal read. See the generated example in Configure your study.

File What is in it
carp_mobile_sensing.json.dart Registers every CAMS class for deserialization
domain.g.dart, runtime.g.dart Generated by json_serializable

Extension to CAMS often rely on serialization to/from JSON - this applies for triggers, measures, sampling schemas, data, etc. CAMS relies on polymorphic serialization as supported by the carp_serializable package, which is an extension to the standard json_serializable provided in Dart.

Support for polymorphic JSON serialization implies four steps when designing your classes:

  1. Define a serializable class

    Extend from Serializable and annotate the class:

    @JsonSerializable(includeIfNull: false, explicitToJson: true)
    class FreeMemory extends Data {
    ...
    }
  2. JSON serializable methods

    Implement the three JSON serializable methods:

    @override
    Function get fromJsonFunction => _$FreeMemoryFromJson;
    factory FreeMemory.fromJson(Map<String, dynamic> json) =>
    FromJsonFactory().fromJson<FreeMemory>(json);
    @override
    Map<String, dynamic> toJson() => _$FreeMemoryToJson(this);
  3. Registration

    Register the class’s fromJsonFunction in the FromJsonFactory, e.g. in the onRegister() callback function of a sampling package:

    @override
    void onRegister() {
    FromJsonFactory()
    .register(FreeMemory()));
    }
  4. Running the code generator

    When all JSON classes have been implemented, the final step is to generate the JSON serialization helper classes. These can be generated using build_runner, by running the following command in the root of your Flutter project:

    Terminal window
    dart run build_runner build --delete-conflicting-outputs

    This will generate the necessary .g.dart files.