Jackson mapper with a common class in scala

I am trying to serialize GeneralResponse:

case class GeneralResponse[T](succeeded: Boolean, payload: Option[T])

and payload GroupsForUserResult:

case class GroupsForUserResult(groups: Seq[UUID]).

I use mapper.readValue(response.body, classOf[GeneralResponse[GroupsForUserResult]]), but unfortunately, the payload is serialized as Map, rather than as the desired case ( GroupForUserResult) class .

+4
source share
2 answers

Due to Java Erasure - Jackson can't know at run time about the generic type T from a string -

mapper.readValue(response.body, classOf[GeneralResponse[GroupsForUserResult]])

The solution to this problem will be

mapper.readValue(json, new TypeReference[GeneralResponse[GroupsForUserResult]] {})

This way you provide an instance TypeReferencewith all the necessary type information.

+4
source

The accepted answer is pretty close, but you should also specify a type parameter .readValue,

import com.fasterxml.jackson.core.`type`.TypeReference
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import org.scalatest.{FunSuite, Matchers}

case class Customer[T](name: String, address: String, metadata: T)

case class Privileged(desc: String)

class ObjectMapperSpecs extends FunSuite with Matchers {

  test("deserialises to case class") {

    val objectMapper = new ObjectMapper()
      .registerModule(DefaultScalaModule)

    val value1 = new TypeReference[Customer[Privileged]] {}

    val response = objectMapper.readValue[Customer[Privileged]](
      """{
           "name": "prayagupd",
           "address": "myaddress",
           "metadata": { "desc" : "some description" }
         }
      """.stripMargin, new TypeReference[Customer[Privileged]] {})

    response.metadata.getClass shouldBe classOf[Privileged]
    response.metadata.desc shouldBe "some description"
  }

}

com.fasterxml.jackson.databind.ObjectMapper#readValue,

public <T> T readValue(String content, TypeReference valueTypeRef)
    throws IOException, JsonParseException, JsonMappingException
{
    return (T) _readMapAndClose(_jsonFactory.createParser(content), _typeFactory.constructType(valueTypeRef));
} 

, Customer cannot be cast to scala.runtime.Nothing$

+1

Source: https://habr.com/ru/post/1584101/


All Articles