I have a question related to fasterxml jackson in serialising a scala class Genre with a Set as one of the fields Set[Type] where Type is a case class with single param value
class Type(val value: String) extends AnyVal
case class Genre(name: String, types: Set[Type])
When I try to serialise it , it gives something like
{"genre":{"name":"xxxxxx","types":[{"value":"aaaaa"}, {"value":"bbbb"}, {"value":"ccccc"}]}}
But I don't want the generated json to contain the param name of the class and it should contain only param value . It should simply look like a comma separated values ["aaaaa","bbbb","ccccc"] something like
{"genre":{"name":"xxxxxx","types":["aaaaa","bbbb","ccccc"]}}
Is there any way , using jackson, to serialise a Set of classes with simply values in it but not param names ?
My mapper looks like this
private val mapper = new ObjectMapper
mapper.registerModule(DefaultScalaModule)
Thanks in Advance !
It should simply look like a comma separated values ["aaaaa","bbbb","ccccc"]
That is Set[String]
, but what you have is Set[Type]
. Jackson is doing exactly what it's supposed to do. You need to change your class signature to:
case class Genre(name: String, types: Set[String])
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule
object TestObject {
def main(args: Array[String]): Unit = {
val mapper = new ObjectMapper()
mapper.registerModule(DefaultScalaModule)
val genre = Genre("xxxxxx", Set(new Type("aaaaa"), new Type("bbbb"), new Type("ccccc")))
println("Genre: " + mapper.writeValueAsString(genre))
val anotherGenre = AnotherGenre("xxxxxx", Set("aaaaa", "bbbb", "ccccc"))
println("AnotherGenre: " + mapper.writeValueAsString(anotherGenre))
}
}
class Type(val value: String) extends AnyVal
case class Genre(name: String, types: Set[Type])
case class AnotherGenre(name: String, types: Set[String])
Output:
Genre: {"name":"xxxxxx","types":[{"value":"aaaaa"},{"value":"bbbb"},{"value":"ccccc"}]}
AnotherGenre: {"name":"xxxxxx","types":["aaaaa","bbbb","ccccc"]}