plokhotnyuk / jsoniter-scala

Scala macros for compile-time generation of safe and ultra-fast JSON codecs + circe booster
MIT License
747 stars 98 forks source link

Support for skipping serialization manually #1041

Closed doohochang closed 1 year ago

doohochang commented 1 year ago

Is there a way to skip serialization for some fields without adding default values for them?

In our project, GraphQL and REST API are served simultaneously from shared Scala entities as following.

// entity used only for serialization, not deserialization.
case class SomeEntity(
    // normal fields
    id: String,
    name: Option[String],

    // fields only for GraphQL
    otherEntity1: IO[Error, OtherEntity1],
    otherEntity2: IO[Error, OtherEntity2],
)

otherEntity1 and otherEntity2 must be excluded during jsoniter serialization. But we don't want to use TransientDefault option, because adding default values to fields can cause some unexpected runtime error due to the lack of type safety.

Is there any workaround to skip the fields manually?

I've tried some workarounds such as defining a codec for IO types that does nothing or just serialize None value in encode function, but field keys don't disappear as I intended.

{
    "id": "...",
    "name": "...",
    "otherEntity1": null,
    "otherEntity2": null
}
plokhotnyuk commented 1 year ago

@doohochang Hi, Dooho! Thanks for trying jsoniter-scala and sending feedback!

Automatic codec derivation require default value definitions for fields that can be omitted in the JSON representation. The only option for your case is writing a custom codec.

doohochang commented 1 year ago

Hi @plokhotnyuk ! Thanks for the reply. It works, but also requires the default value for the field. I'm going to write a custom codec derivation for this case as you said.

Is it a possible or considerable option to support more field skipping options such as below?

I think they might help some cases that require only serialization, except for deserialization.

plokhotnyuk commented 1 year ago

As an option you can try separated case class for JSON representation with boilerplate free transformation with the chimney library.

doohochang commented 1 year ago

We want to avoid separated entity classes as possible as we can, as it still affects our productivity despite the useful transformation libraries.

I think customized macro derivation can be implemented for our edge cases, so I'll close this issue for now :)

Always thank you for your amazing contribution!