1

我有一个 dart 对象,其中包含一个 type 字段Money,该字段本身由amountand组成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实例中获取两个值并将它们映射到balanceAmountbalanceCurrency

我在json_serializableapi 文档、GitHub 问题或 StackOverflow 上所做的搜索似乎没有特别回应这一点:如何将一个字段映射到两个(或更多)目标键?

4

1 回答 1

0

如果生成的代码像这样使用完整的 json,这个解决方案会更好"balance"

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
// }
于 2022-01-18T18:42:07.690 回答