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

ShortTypeHints does not work with object #1162

Open
delenius opened this issue Nov 1, 2022 · 1 comment
Open

ShortTypeHints does not work with object #1162

delenius opened this issue Nov 1, 2022 · 1 comment

Comments

@delenius
Copy link

delenius commented Nov 1, 2022

json4s version

4.1.0-M2

scala version

2.13.10

jdk version

AdoptOpenJDK Java 11.0.6

Example to reproduce below. The first test succeeds. The second test fails.

import org.json4s.ShortTypeHints
import org.json4s.native.Serialization
import org.scalatest.funsuite.AnyFunSuite

trait TopTrait

case class EmptyCaseClass() extends TopTrait

object AnObject extends Top

class JsonObjectTest extends AnyFunSuite {

  implicit val formats = Serialization.formats(ShortTypeHints(List(
    classOf[EmptyCaseClass],
    AnObject.getClass
  ), "node_type"))

  test("Empty Case Class") {
    val jsonStr =
      """{
        |   "node_type": "EmptyCaseClass"
        |}
        |""".stripMargin
    val result = Serialization.read[TopTrait](jsonStr)
    println(result)
  }

  test("Object") {
    val jsonStr =
      """{
        |   "node_type": "AnObject"
        |}
        |""".stripMargin
    val result = Serialization.read[TopTrait](jsonStr)
    println(result)
  }

}
@plokhotnyuk
Copy link
Contributor

@delenius Assuming that object AnObject extends TopTrait.

If your trait can be sealed then you can use jsoniter-scala as a workaround:

import org.scalatest.funsuite.AnyFunSuite
import com.github.plokhotnyuk.jsoniter_scala.core._
import com.github.plokhotnyuk.jsoniter_scala.macros._

sealed trait TopTrait

case class EmptyCaseClass() extends TopTrait

object AnObject extends TopTrait

class JsonObjectTest extends AnyFunSuite {

  implicit val codec: JsonValueCodec[TopTrait] =
    JsonCodecMaker.make[TopTrait](CodecMakerConfig.withDiscriminatorFieldName(Some("node_type")))

  test("Empty Case Class") {
    val jsonStr =
      """{
        |   "node_type": "EmptyCaseClass"
        |}
        |""".stripMargin
    val result = readFromString[TopTrait](jsonStr)
    println(result)
  }

  test("Object") {
    val jsonStr =
      """{
        |   "node_type": "AnObject"
        |}
        |""".stripMargin
    val result = readFromString[TopTrait](jsonStr)
    println(result)
  }

}

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

No branches or pull requests

2 participants