Skip to content

Commit

Permalink
Merge pull request #45 from bowbahdoe/cleanup-feb-25
Browse files Browse the repository at this point in the history
Add example and mark functional interface
  • Loading branch information
bowbahdoe authored Feb 26, 2023
2 parents fa1aa94 + eeed189 commit e094dab
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
63 changes: 63 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1304,4 +1304,67 @@ Movie(Most wanted,List(Muppet(kermit,false,Some(kermit)), Muppet(beaker,true,Som
Movie(Most wanted,List(Muppet(kermit,false,Some(I'm not Constantine!)), Muppet(beaker,true,None), Muppet(bunsen,true,Some(I don't mean to be a stickler))))
false
```
</details>

### Decode into sealed trait with Scala 3

<details>
<summary>Show</summary>

```scala
import dev.mccue.json.{Json, JsonDecodeException, JsonDecoder, JsonEncodable, JsonWriteOptions}

import scala.jdk.CollectionConverters.*

sealed trait MessageBody {
def messageId: Int
}

object MessageBody {
def fromJson(json: Json): MessageBody = {
val id = JsonDecoder.field(json, "type", JsonDecoder.string _)
id match
case "init" =>
Init(
JsonDecoder.field(json, "msg_id", JsonDecoder.int_ _),
JsonDecoder.field(json, "node_id", JsonDecoder.string _),
JsonDecoder.field(json, "node_ids", JsonDecoder.array(JsonDecoder.string _))
.asScala
.toSeq
)
case "init_ok" =>
InitOk(
JsonDecoder.field(json, "msg_id", JsonDecoder.int_ _),
JsonDecoder.field(json, "in_reply_to", JsonDecoder.int_ _)
)
case _ =>
throw JsonDecodeException.atField("type", JsonDecodeException.of(
"expected one of \"init\", \"init_ok\"",
json
))
}
}

case class Init(messageId: Int, nodeId: String, nodeIds: Seq[String]) extends MessageBody {}
case class InitOk(messageId: Int, inReplyTo: Int) extends MessageBody {}

case class Envelope(src: Option[String], dest: Option[String], body: MessageBody) {}

object Envelope {
def fromJson(json: Json): Envelope = {
Envelope(
JsonDecoder.optionalField(json, "src", JsonDecoder.string _)
.map(Option(_))
.orElse(None),

JsonDecoder.optionalField(json, "dest", JsonDecoder.string _)
.map(Option(_))
.orElse(None),

JsonDecoder.field(json, "body", MessageBody.fromJson _)
)
}
}
```

</details>
1 change: 1 addition & 0 deletions src/main/java/dev/mccue/json/JsonDecoder.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
*
* @param <T> The type that being constructed from the Json.
*/
@FunctionalInterface
public interface JsonDecoder<T> {
/**
* Interpret some {@link Json} as some type.
Expand Down

0 comments on commit e094dab

Please sign in to comment.