stringKey
Key codec for String (identity).
Attributes
- Source
- JsonKeyCodec.scala
- Graph
-
- Supertypes
- Self type
-
stringKey.type
Members list
Value members
Concrete methods
Decodes a JSON object field name to a key.
Decodes a JSON object field name to a key.
Value parameters
- key
-
the field name
Attributes
- Returns
-
either a decode failure or the decoded key
- Source
- JsonKeyCodec.scala
Encodes a key to a JSON object field name.
Encodes a key to a JSON object field name.
Value parameters
- key
-
the key to encode
Attributes
- Returns
-
the field name
- Source
- JsonKeyCodec.scala
Inherited methods
Invariant mapping for key codecs.
Invariant mapping for key codecs.
Creates a JsonKeyCodec[L] from an existing JsonKeyCodec[K] using total conversions between K and L.
Value parameters
- from
-
conversion from L to K
- to
-
conversion from K to L
Attributes
- Example
-
case class UserId(value: Int) given JsonKeyCodec[UserId] = JsonKeyCodec[Int].imap(UserId(_), _.value) - Inherited from:
- JsonKeyCodec
- Source
- JsonKeyCodec.scala
Narrows this codec with decode-time validation only.
Narrows this codec with decode-time validation only.
Creates a JsonKeyCodec[L] from an existing JsonKeyCodec[K] where the forward transformation to: K => Either[DecodeFailure, L] may fail (affecting decoding), while the backward transformation from: L => K is total (used for encoding).
Use this when you want to refine keys during decoding (e.g. constrain numeric ranges or string formats) but can always project refined keys back to the base representation for encoding.
Value parameters
- from
-
total conversion from L to K (used on encode)
- to
-
conversion from K to L with validation (used on decode)
Attributes
- Note
-
If you need total conversions in both directions, prefer imap. If you need encode-time validation (L => Either[DecodeFailure, K]), design your key type so that
fromis total, and validate onto. - Example
-
// Refine Int keys to positive-only keys for decoding, while encoding via Int final case class PositiveKey private (value: Int) object PositiveKey: def fromInt(n: Int): Either[DecodeFailure, PositiveKey] = Either.cond( n > 0, PositiveKey(n), DecodeFailure(s"Not positive: $n"), ) given JsonKeyCodec[PositiveKey] = JsonKeyCodec[Int].narrow(PositiveKey.fromInt, _.value) // Map keys are validated on decode and rendered as their base Int on encode val json = JsonEncoder[Map[PositiveKey, String]].encode( Map(PositiveKey(1) -> "ok"), ) val roundtrip = JsonDecoder[Map[PositiveKey, String]].decode(json) - Inherited from:
- JsonKeyCodec
- Source
- JsonKeyCodec.scala