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

Fix ClassCastException for hierarchical enum JSON encoding

Open SolariSystems opened this issue 2 months ago • 10 comments

Fixes #668

Problem

When using JSON codec with auto-derived schemas for hierarchical sealed trait enums (e.g., Animal > Mammal > Bison), encoding fails with ClassCastException: Schema$Enum1 cannot be cast to Schema$CaseClass0.

Root Cause

The JsonCodec implementation incorrectly assumed all enum cases have CaseClass0 schemas. However, intermediate sealed traits in hierarchical enums have Enum schemas, not CaseClass0.

Solution

  • Added constructEnumCase helper function that pattern matches on case schema type
  • Handles both CaseClass0 and Enum case schemas correctly
  • Uses the proper Case.construct method for type-safe construction
  • Updated three locations in JsonCodec.scala that made the incorrect assumption

Changes

  • zio-schema-json/shared/src/main/scala/zio/schema/codec/JsonCodec.scala: Fix + helper function
  • zio-schema-json/shared/src/test/scala/zio/schema/codec/JsonCodecSpec668.scala: Regression tests

Testing

Added regression test suite covering:

  • Simple hierarchical enum (Animal > Mammal > Bison)
  • Deeper hierarchy (Vehicle > LandVehicle > Car > Sedan)
  • Round-trip encoding/decoding

CI will validate compilation and test suite passes.

SolariSystems avatar Dec 22 '25 21:12 SolariSystems

You made non-needed changes by replacing toArray in other places. Also, the constructEnumCase should be just private (not package private). And you have pushed all that in a wrong branch: https://github.com/zio/zio-schema/pull/967/changes/3b6f9ed649563fa9985c05bcc88d8b55d8bfac83

plokhotnyuk avatar Dec 23 '25 08:12 plokhotnyuk

@SolariSystems Please use more advanced ADT with leaf classes on different levels of hierarchy in tests.

One of real-word ADTs that could be reused for tests is this GeoJSON hierarchy

plokhotnyuk avatar Feb 21 '26 16:02 plokhotnyuk