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.
Where in the repo
Section titled “Where in the repo”| 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 |
How it works
Section titled “How it works”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:
Define a serializable class
Extend from
Serializableand annotate the class:@JsonSerializable(includeIfNull: false, explicitToJson: true)class FreeMemory extends Data {...}JSON serializable methods
Implement the three JSON serializable methods:
@overrideFunction get fromJsonFunction => _$FreeMemoryFromJson;factory FreeMemory.fromJson(Map<String, dynamic> json) =>FromJsonFactory().fromJson<FreeMemory>(json);@overrideMap<String, dynamic> toJson() => _$FreeMemoryToJson(this);Registration
Register the class’s
fromJsonFunctionin theFromJsonFactory, e.g. in theonRegister()callback function of a sampling package:@overridevoid onRegister() {FromJsonFactory().register(FreeMemory()));}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-outputsThis will generate the necessary
.g.dartfiles.