ValueMap Serialization
This page describes how ValueMap<TKey, TValue> is serialized and deserialized with JsonSerializer.
For general ValueMap behavior and API, see ValueMap.
Why This Matters
Section titled “Why This Matters”When dictionaries with complex keys are serialized from the backend, key objects are represented as JSON property names. During frontend deserialization, you often create new key instances for lookups, which do not match by reference.
ValueMap with JsonSerializer and @field metadata ensures these entries are reconstructed as typed keys and values.
Field Metadata and Generic Arguments
Section titled “Field Metadata and Generic Arguments”To deserialize a ValueMap with typed keys and typed values, provide generic arguments through the @field decorator options:
import { field, ValueMap } from '@cratis/fundamentals';
class AccountKey { @field(String) tenant!: string;}
class AccountSummary { @field(Number) balance!: number;}
class Projection { @field(ValueMap, { genericArguments: [AccountKey, AccountSummary] }) accounts!: ValueMap<AccountKey, AccountSummary>;}Behavior
Section titled “Behavior”- Keys are deserialized using the first generic argument.
- Values are deserialized using the second generic argument, the same way a value of that type is read
anywhere else — so
String,NumberandBooleancome back as primitives, aConceptAstype comes back wrapped, and a type with a registered converter goes through it. - Lookup with a new key instance works when key content is equal.
- With the built-in
Dateconverter, ISO keys that differ below a millisecond remain distinct and retain their precision when written back. The keys are stillDateinstances. Use the keys returned byentries()to look up sub-millisecond instants; a newDatecannot represent that precision.
Example
Section titled “Example”This continuation uses the imports and decorated AccountKey, AccountSummary and Projection declarations above. The payload represents the account key as a JSON property name; deserialization reconstructs the key and summary before the lookup:
import { JsonSerializer } from '@cratis/fundamentals';
const json = JSON.stringify({ accounts: { [JSON.stringify({ tenant: 'tenant-a' })]: { balance: 1200 } }});const projection = JsonSerializer.deserialize(Projection, json);
const key = new AccountKey();key.tenant = 'tenant-a';
const summary = projection.accounts.get(key);console.log(summary?.balance); // 1200
projection.accounts.set(key, { balance: 1200 });
for (const [accountKey, accountSummary] of projection.accounts.entries()) { console.log(accountKey.tenant, accountSummary.balance);}Backend Interop
Section titled “Backend Interop”For backend serialization details, see Complex Key Dictionaries.