Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Why can't Gson serialize the value of the scala.collection.immutable.Map type member variable of the case class into a JSON string,while java.util.HashMap is ok? #2601

Open
4 tasks
Ivankings opened this issue Jan 19, 2024 · 1 comment

Comments

@Ivankings
Copy link

Ivankings commented Jan 19, 2024

Gson version

gson version 2.85

Java / Android version

Java version 1.8.0_392
Scala version 2.12.15

Used tools

  • Maven; version:
  • Gradle; version:
  • ProGuard (attach the configuration file please); version:
  • ...

Description

Expected behavior

Actual behavior

Reproduction steps

case class Config(info: scala.collection.immutable.Map[String, String])
case class ConfigHashMap(info: java.util.HashMap[String, String])

val map = scala.collection.immutable.Map("k" -> "v")
val hashMap = new java.util.HashMap[String, String]()
hashMap.put("k", "v")

val config = Config(map)
val configHashMap = ConfigHashMap(hashMap)

import com.google.gson.Gson;
val g = new Gson()
g.toJson(config)
g.toJson(configHashMap)
image

Exception stack trace


@Ivankings Ivankings added the bug label Jan 19, 2024
@Marcono1234
Copy link
Collaborator

Marcono1234 commented Jan 20, 2024

Gson has no explicit support for Scala, it might work for some cases but not for all. I am not familiar with Scala, but I assume scala.collection.immutable.Map does not implement java.util.Map, so Gson falls back to using reflection and apparently that does not work well here. And even if it worked you would rely on the implementation details of Scala's Map because Gson just accesses all fields, even if they are private.

You might be able to solve this by writing a custom TypeAdapterFactory for Scala's Map type. However, a better solution is probably to switch to a JSON library with explicit Scala support.

Does that answer your question?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants