我有一个dart对象,它包括一个类型为Money
的字段,它本身由amount
和currency
:组成
@JsonSerializable()
class Account {
final String id;
final String type;
final String subtype;
final String origin;
final String name;
final String status;
final String currency;
final Money balance; <== value object
...
}
Money
看起来像这样:
class Money {
final int amount;
final String currency;
const Money(this.amount, this.currency);
...
}
以上内容将被映射以供sqflite
使用,因此目标JSON必须是一个平面JSON,如:
{
"id": String,
"type": String,
"subtype": String,
"origin": String,
"name": String,
"status": String,
"currency": String,
"balanceAmount": int; <== value object
"balanceCurrency": String; <== value object
}
我知道我可以在解码之前使用JsonKey.readValue
从整个JSON对象中提取一个复合对象。
但是我怎么能做相反的事情呢?从Money
实例中获取两个值,并将它们映射到balanceAmount
和balanceCurrency
我在json_serializable
api文档、GitHub问题或StackOverflow上进行的搜索似乎没有特别回应这一点:如何将一个字段映射到两个(或多个(目标键?
如果生成的代码在"balance"
中使用完整的json,这个解决方案会更好像这样:
Money.fromJson(json(
但我不知道该怎么做:(
import 'package:project/test/money.dart';
import 'package:json_annotation/json_annotation.dart';
part 'account.g.dart';
@JsonSerializable()
class Account {
final String id;
final String type;
final String subtype;
final String origin;
final String name;
final String status;
final String currency;
@JsonKey(fromJson: _dataFromJson)
final Money balance; // <== value object
Account({
required this.id,
required this.type,
required this.subtype,
required this.origin,
required this.name,
required this.status,
required this.currency,
required this.balance,
});
static Money _dataFromJson(Object json) {
if (json is Map<String, dynamic>) {
return Money(amount: json["balanceAmount"], currency: json["balanceCurrency"]);
}
throw ArgumentError.value(
json,
'json',
'Cannot convert the provided data.',
);
// return Money(amount: 0, currency:"");
}
factory Account.fromJson(Map<String, dynamic> json) => Account(
id: json['id'] as String,
type: json['type'] as String,
subtype: json['subtype'] as String,
origin: json['origin'] as String,
name: json['name'] as String,
status: json['status'] as String,
currency: json['currency'] as String,
balance: Money.fromJson(json),
);
Map<String, dynamic> toJson() => _$AccountToJson(this);
}
// {
// "id": String,
// "type": String,
// "subtype": String,
// "origin": String,
// "name": String,
// "status": String,
// "currency": String,
// "balanceAmount": int; <== value object
// "balanceCurrency": String; <== value object
// }