jsoniter-scala icon indicating copy to clipboard operation
jsoniter-scala copied to clipboard

add case class instance val to writer codec

Open benoit-ponsero opened this issue 3 years ago • 1 comments

Hello,

I wonder if it's possible to add variable class automatically to codec (using macro).

exemple: `case class Margin(price:BigDecimal, purchase:BigDecimal){

val amount = price - purchase

val rate = { if (price == BigDecimal(0)) BigDecimal(0) else amount / price }

}`

I want that the writer codec print the fields price, purchase plus the fields amount & rate.

I know i can create a custom codec from scratch, but it will be cool if we can have an annotation to mark a field as serializable or even extend the default one to add this 2 fields.

(this exemple is trivial, my thoughts are more for complex case class with lot of fields)

Thanks

benoit-ponsero avatar May 09 '22 09:05 benoit-ponsero

Hi, @benoit-ponsero!

The main idea of codec derivation with macro to allow round trip serialization and parsing without data loss, so such kind of options will not be added for derivation macros.

But the problem can be solved if you have an ability to refactor your data structures to have the private constructor with all fields need to be serializable and the corresponding object with an implicit val for the derived codec and apply method for construction with pre-calculated fields, like here:

case class Margin private(price: BigDecimal, purchase: BigDecimal, amount: BigDecimal, rate: BigDecimal)

object Margin {
  implicit val codec: JsonValueCodec[Margin] = make

  def apply(price: BigDecimal, purchase: BigDecimal): Margin = {
    val amount = price - purchase
    val rate = {
      if (price == BigDecimal(0)) BigDecimal(0) else amount / price
    }
    Margin(price, purchase, amount, rate)
  }
}

plokhotnyuk avatar May 09 '22 09:05 plokhotnyuk