Closed stanislav-chetvertkov closed 2 months ago
the same behaviour also appears when using
import zio.json.DecoderOps
...
string.fromJson[Example]
I was able to make it work by changing recordDecoder
method in zio.schema.codec.JsonCodec
to look like this
private def recordDecoder[Z](structure: Seq[Schema.Field[Z, _]]): ZJsonDecoder[ListMap[String, Any]] = {
(trace: List[JsonError], in: RetractReader) => {
val builder: ChunkBuilder[(String, Any)] = zio.ChunkBuilder.make[(String, Any)](structure.size)
Lexer.char(trace, in, '{')
if (Lexer.firstField(trace, in)) {
while ( {
val field = Lexer.string(trace, in).toString
structure.find(_.name == field) match {
case Some(Schema.Field(label, schema, _, _, _, _)) =>
val trace_ = JsonError.ObjectAccess(label) :: trace
Lexer.char(trace_, in, ':')
val value = schemaDecoder(schema).unsafeDecode(trace_, in)
builder += ((JsonFieldDecoder.string.unsafeDecodeField(trace_, label), value))
case None =>
Lexer.char(trace, in, ':')
Lexer.skipValue(trace, in)
}
(Lexer.nextField(trace, in))
}) {
()
}
}
val tuples = builder.result()
val collectedFields: Set[String] = tuples.map { case (fieldName, _) => fieldName }.toSet
val resultBuilder = ListMap.newBuilder[String, Any]
// add fields with default values if they are not present in the JSON
structure.foreach { field =>
if (!collectedFields.contains(field.name)) {
val value = field.name -> field.defaultValue.get
resultBuilder += value
}
}
(resultBuilder ++= tuples).result()
}
}
so that it adds fields with their default values from the schema if they were not present in the input JSON
I'm going create a pr containing the change soon
JsonCodec.jsonDecoder
does not seem to work with schemas derived from case classes with more than 22 fields, in the following exampleIt returns
Example(Some(test),None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None)
but when I uncomment
f23: Option[String] = None
I get(Field f2 is missing)
error It could be due to some inconsistencies handling CaseClass22 and GenericRecord (for 23 or more fields) schemas