Fix ClassCastException for hierarchical enum JSON encoding
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
constructEnumCasehelper function that pattern matches on case schema type - Handles both
CaseClass0andEnumcase schemas correctly - Uses the proper
Case.constructmethod for type-safe construction - Updated three locations in
JsonCodec.scalathat 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.
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
@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