google / google/json_serializable.dart

Use dart json_serializable to map an object field to JSON flat keys (one to many mapping)

Open
#1,074 2 comments 12 reactions 0 assignees View on GitHub
Dominant language
Dart
Stars
1.6k
Forks
461
Avg merge
45m
Merged PRs (30d)
1

Description

I have a dart object that includes a field of type `Money`, which itself is composed of `amount` and `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` looks something like this:

```
class Money {
final int amount;
final String currency;

const Money(this.amount, this.currency);
...
}
```

The above is to be mapped for use by `sqflite`, therefore the target JSON must be a flat JSON, like:

```
{
"id": String,
"type": String,
"subtype": String,
"origin": String,
"name": String,
"status": String,
"currency": String,
"balanceAmount": int; <== value object
"balanceCurrency": String; <== value object
}
```

I understand I can use `JsonKey.readValue` to extract a composite object from the entire JSON object prior to decoding.

**But how can I do the opposite? Grab the two values from the `Money` instance and map them to `balanceAmount` and `balanceCurrency`?**

Nothing in the search I did on `json_serializable` api docs, GitHub issues, or StackOverflow appears to respond to this in particular: how to map one field to two (or more) target keys?

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.