record4s

Integration with circe

Records can be converted to/from JSON by using circe.

Installation

You need an additional module to use records integrated with circe.

libraryDependencies ++= Seq(
  "com.github.tarao" %% "record4s-circe" % "0.13.0"
),

To JSON

Importing Codec.encoder enables circe to encode records in the ordinary way.

import com.github.tarao.record4s.%
import com.github.tarao.record4s.circe.Codec.encoder
import io.circe.generic.auto.*
import io.circe.syntax.*

val r = %(name = "tarao", age = 3)
// r: % {
//   val name: String
//   val age: Int
// } = %(name = tarao, age = 3)
val json = r.asJson.noSpaces
// json: String = "{\"name\":\"tarao\",\"age\":3}"

From JSON

Importing Codec.decoder enables circe to decode records in the ordinary way.

import com.github.tarao.record4s.%
import com.github.tarao.record4s.circe.Codec.decoder
import io.circe.generic.auto.*
import io.circe.parser.parse

val json = """{"name":"tarao","age":3}"""
// json: String = "{\"name\":\"tarao\",\"age\":3}"
val r =
  for {
    jsonObj <- parse(json)
  } yield jsonObj.as[% { val name: String; val age: Int }]
// r: Either[ParsingFailure, Result[% {
//   val name: String
//   val age: Int
// }]] = Right(
//   value = Right(value = %(name = tarao, age = 3))
// )

ArrayRecord

ArrayRecord requires no additional module since it is a Product, whose conversions are already supported by circe itself.

import com.github.tarao.record4s.ArrayRecord
import io.circe.generic.auto.*
import io.circe.syntax.*

val r = ArrayRecord(name = "tarao", age = 3)
// r: ArrayRecord[*:[Tuple2["name", String], *:[Tuple2["age", Int], EmptyTuple]]] = ArrayRecord(
//   name = "tarao",
//   age = 3
// )
val json = r.asJson.noSpaces
// json: String = "{\"name\":\"tarao\",\"age\":3}"
import com.github.tarao.record4s.ArrayRecord
import io.circe.generic.auto.*
import io.circe.parser.parse

val json = """{"name":"tarao","age":3}"""
// json: String = "{\"name\":\"tarao\",\"age\":3}"
val r =
  for {
    jsonObj <- parse(json)
  } yield jsonObj.as[ArrayRecord[(("name", String), ("age", Int))]]
// r: Either[ParsingFailure, Result[ArrayRecord[Tuple2[Tuple2["name", String], Tuple2["age", Int]]]]] = Right(
//   value = Right(value = ArrayRecord(name = "tarao", age = 3))
// )