zio-json icon indicating copy to clipboard operation
zio-json copied to clipboard

Support enum encoding

Open jgoday opened this issue 3 years ago • 7 comments

From #105.

It allows to encode/decode enums (as sealed traits and case objects) like

   sealed trait Color
   case object Green extends Color
   case object Yellow extends Color

I think that some things needs some revision or maybe a different/better solution:

1 - When decoding a SealedTrait, lexer tries to consumes '{', if it throws an UnsafeJson exception, we try to match an enum value. 2 - Find a better approach to determine if an object is a case object (should work in scala.js too)

def isCaseObject(x: Any): Boolean = x.getClass.getName.endsWith("$")

jgoday avatar May 15 '21 16:05 jgoday

@fommil I’d appreciate your opinion here.

fsvehla avatar May 16 '21 12:05 fsvehla

conceptually this is nice but it is too magical for my personal tastes. I'd rather this was its own macro. Firstly it breaks backwards compatibility, and secondly it means that your entire sealed trait encoding can change just because you add a non case object.

fommil avatar May 16 '21 19:05 fommil

conceptually this is nice but it is too magical for my personal tastes. I'd rather this was its own macro. Firstly it breaks backwards compatibility, and secondly it means that your entire sealed trait encoding can change just because you add a non case object.

I agree, especially regarding the backwards compatibility and the lexer/exceptions part. It was just an attempt to implement that use case and experimenting with the existing codebase. Please, remove the PR if necessary.

jgoday avatar May 17 '21 19:05 jgoday

@jgoday If we implement this with another macro, we could keep compatibility and fail compilation if not every member of the sealed hierarchy is a case object — wdyt?

fsvehla avatar May 17 '21 20:05 fsvehla

@jgoday If we implement this with another macro, we could keep compatibility and fail compilation if not every member of the sealed hierarchy is a case object — wdyt?

@fsvehla Sounds good, what should it be called (instead of DeriveJsonDecoder) ?

jgoday avatar May 18 '21 20:05 jgoday

@jgoday DeriveJsonDecoderEnum?

fsvehla avatar May 19 '21 21:05 fsvehla

@fsvehla, I have implemented it like this https://github.com/jgoday/zio-json/commit/2f7160a34e37d60b56bf556796920f255fde39fd

Two different macros (DeriveJsonDecoderEnum/DeriveJsonEncoderEnum) only for the sealed traits/case objects like enums.

Is this a valid approach ? If so, we should implement toJsonAST/fromJsonAST tests and keep running existing annotations with the new encoder/decoder for enums.

jgoday avatar May 21 '21 20:05 jgoday