Skip to content

Commit

Permalink
Fix mdoc
Browse files Browse the repository at this point in the history
  • Loading branch information
erikvanoosten committed Apr 23, 2024
1 parent e994c46 commit 214ec0a
Showing 1 changed file with 18 additions and 8 deletions.
26 changes: 18 additions & 8 deletions docs/decoding.md
Original file line number Diff line number Diff line change
Expand Up @@ -197,12 +197,19 @@ final case class Quote(
)
```

All approaches result in the same result:

```scala mdoc:fail
"""{"01. symbol":"IBM","02. open": "182.4300","03. high": "182.8000"}""".fromJson[Quote]
// >> Right(Quote(IBM,182.4300,182.8000))
```

## Approach 1: use annotation hints

In this approach we enrich the case class with annotations to tell the derived decoder which field names to use.
Obviously, this approach only works if we can/want to change the case class.

```scala mdoc
```scala mdoc:reset
import zio.json._

final case class Quote(
Expand All @@ -214,19 +221,18 @@ final case class Quote(
object Quote {
implicit val decoder: JsonDecoder[Quote] = DeriveJsonDecoder.gen[Quote]
}

"""{"01. symbol":"IBM","02. open": "182.4300","03. high": "182.8000"}""".fromJson[Quote]
// >> Right(Quote(IBM,182.4300,182.8000))
```

## Approach 2: use an intermediate case class

Instead of hints, we can also put the actual field names in an intermediate case class. In our example the field names
are not valid scala identifiers. We fix this by putting the names in backticks:

```scala mdoc
```scala mdoc:reset
import zio.json._

final case class Quote(symbol: String, open: String, high: String)

object Quote {
private final case class JsonQuote(
`01. symbol`: String,
Expand All @@ -249,10 +255,12 @@ extract data from any valid JSON.
Note that this implementation is a bit sloppy. It uses `toString` on a JSON node. The node is not necessarily a
String, it can be of any JSON type! So this might happily process JSON that doesn't match your expectations.

```scala mdoc
```scala mdoc:reset
import zio.json._
import zio.json.ast.Json

final case class Quote(symbol: String, open: String, high: String)

object Quote {
implicit val decoder: JsonDecoder[Quote] = JsonDecoder[Json]
.mapOrFail {
Expand All @@ -279,10 +287,12 @@ object Quote {
Here we also first decode to `Json`, but now we use cursors to find the data we need. Here we do check that the fields
are actually strings.

```scala mdoc
```scala mdoc:reset
import zio.json._
import zio.json.ast.{Json, JsonCursor}

final case class Quote(symbol: String, open: String, high: String)

object Quote {
private val symbolC = JsonCursor.field("01. symbol") >>> JsonCursor.isString
private val openC = JsonCursor.field("02. open") >>> JsonCursor.isString
Expand All @@ -307,7 +317,7 @@ both cases.

Here's a custom decode for our Animal case class:

```scala mdoc
```scala mdoc:reset
import zio.Chunk
import zio.json._
import zio.json.ast._
Expand Down

0 comments on commit 214ec0a

Please sign in to comment.