Простой способ сериализации / десериализации сложных структур данных в объекты Json заключается в использовании пакета
marshalling
.
Прототип (в формате "yaml")
json_objects.yaml
Customer:
name: String
lastname: String
CustomerList:
customerList: List<Customer>
Автоматическая генерация кода (с помощью утилиты "yaml2podo")
pub global run marshalling:yaml2podo json_objects.yaml
json_objects.dart
// Generated by tool.
import 'package:marshalling/json_serializer.dart';
final json = JsonSerializer()
..addType(() => Customer())
..addType(() => CustomerList())
..addIterableType<List<Customer>, Customer>(() => <Customer>[])
..addAccessor('customerList', (o) => o.customerList, (o, v) => o.customerList = v)
..addAccessor('lastname', (o) => o.lastname, (o, v) => o.lastname = v)
..addAccessor('name', (o) => o.name, (o, v) => o.name = v)
..addProperty<Customer, String>('name')
..addProperty<Customer, String>('lastname')
..addProperty<CustomerList, List<Customer>>('customerList');
class Customer {
String name;
String lastname;
Customer();
factory Customer.fromJson(Map map) {
return json.unmarshal<Customer>(map);
}
Map<String, dynamic> toJson() {
return json.marshal(this) as Map<String, dynamic>;
}
}
class CustomerList {
List<Customer> customerList;
CustomerList();
factory CustomerList.fromJson(Map map) {
return json.unmarshal<CustomerList>(map);
}
Map<String, dynamic> toJson() {
return json.marshal(this) as Map<String, dynamic>;
}
}
Использовать сгенерированный код (автоматическая сериализация / дериализация объектов)
import 'json_objects.dart';
void main() {
var customers = <Customer>[];
var customer = Customer()
..name = 'tom'
..lastname = 'smith';
customers.add(customer);
customer = Customer()
..name = 'bob'
..lastname = 'lee';
customers.add(customer);
customer = Customer()
..name = 'george'
..lastname = 'lee';
customers.add(customer);
var customerList = CustomerList();
customerList.customerList = customers;
var data = customerList.toJson();
// final HttpsCallableResult result = await callable.call(data);
print(data);
}
Результат:
{customerList: [{name: tom, lastname: smith}, {name: bob, lastname: lee}, {name: george, lastname: lee}]}