toObject method
Generic interface representing a parsed node in Jetleaf's structured data model (JSON/YAML/other).
Node<ObjectType> is the canonical abstraction for any parsed value and
intentionally maps to a native Dart type via toObject.
This interface is designed for:
- Providing a uniform API across different node kinds (object, array, string, number, boolean, null)
- Allowing generated or runtime parsers to expose parsed content without forcing callers to depend on parser internals
- Enabling conversions to standard Dart collections and primitives
Usage Example
// When deserializing:
final Node<Map<String, Object?>> root = await parser.parse();
final Map<String, Object?> map = root.toObject();
// Working with arrays:
final Node<List<Object?>> arr = someNode as Node<List<Object?>>;
final list = arr.toObject();
Design Notes
ObjectTypeis the concrete Dart type produced by toObject. Implementors should guarantee the returned value conforms to that type.- Conversions are typically recursive: nested nodes become nested Dart collections (maps / lists).
- The interface is intentionally minimal to keep node implementations small and easily generated for codegen use-cases.
- Prefer returning nullable element types in collections (
Object?) to reflect possiblenullvalues in parsed data.
Example Mapping
| Node Kind | toObject() result type |
|---|---|
| Object | Map<String, Object?> |
| Array | List<Object?> |
| String | String |
| Number | num |
| Boolean | bool |
| Null | null |
See Also
- Parser — streaming token parser that produces nodes
NodeMap,NodeArray,NodeString— typical node implementations- Jetleaf serialization/deserialization utilities
Converts the parsed node into a native Dart object.
The returned object matches the parsed type:
- parsed object →
Map<String, Object?> - parsed array →
List<Object?> - parsed string →
String - parsed number →
num - parsed boolean →
bool - parsed null →
null
Use this method to work with standard Dart collections instead of custom node types.
Example
final map = node.toObject() as Map<String, Object?>;
print(map['name']); // prints the value of the 'name' field
Implementation
@override
Map<String, dynamic> toObject() {
final result = <String, dynamic>{};
if (_attributes.isNotEmpty) {
result['@attributes'] = _attributes;
}
if (_children.isEmpty) {
return result;
}
final textContent = getText();
if (_children.length == 1 && textContent != null && textContent.isNotEmpty) {
result['#text'] = textContent;
} else {
for (final child in _children) {
final childName = child.getName();
if (childName != null) {
final childObj = child.toObject();
if (result.containsKey(childName)) {
if (result[childName] is List) {
(result[childName] as List).add(childObj);
} else {
result[childName] = [result[childName], childObj];
}
} else {
result[childName] = childObj;
}
}
}
}
return result;
}