com-lihaoyi / upickle

uPickle: a simple, fast, dependency-free JSON & Binary (MessagePack) serialization library for Scala
https://com-lihaoyi.github.io/upickle
MIT License
707 stars 158 forks source link

Missing keys exception using Option with generic #545

Closed mobilemindtec closed 5 months ago

mobilemindtec commented 5 months ago

Hello!

I'm getting a missing keys exception when key is a option generic field. Example:


case class Person(id: Int, name: String = "test") derives ReadWriter

case class Person2(id: Int, name: Option[String] = None) derives ReadWriter

case class ApiResult[T](data: Option[T] = None, @key("total_count") totalCount: Int) derives ReadWriter

println(read[Person]("{\"id\":1}"))  // OK

println(read[Person2]("{\"id\":1}"))  // OK

println(read[ApiResult[Person]]("{\"total_count\": 10}")) // Fail

Is there a way to get around this?

lihaoyi commented 5 months ago

Seems like a bug in the Scala 3 macros, the Scala 2 equivalent seems to work

import upickle.implicits.key
case class Person(id: Int, name: String = "test") 
implicit val personRw = upickle.default.macroRW[Person]

case class ApiResult[T](data: Option[T] = None, @key("total_count") totalCount: Int) 
implicit def apiResultRw[T: upickle.default.ReadWriter] = upickle.default.macroRW[ApiResult[T]]
println(upickle.default.read[Person]("{\"id\":1}"))  // OK

println(upickle.default.read[ApiResult[Person]]("{\"total_count\": 10}")) // Works
lihaoyi commented 5 months ago

The problem appears to be that TypeTree.of[T].symbol for ApiResult[T] is val <none>. Exactly why that is the case is unknown to me

lihaoyi commented 5 months ago

@mobilemindtec This fix should have gone out in the latest version 3.1.4