我有一个与fasterxml jackson有关的问题,在序列化scala class genre 中,将集合作为一个字段 set [type] 中 type 是单个param value
的案例类class Type(val value: String) extends AnyVal
case class Genre(name: String, types: Set[Type])
当我尝试序列化时,它会提供
之类的东西{"genre":{"name":"xxxxxx","types":[{"value":"aaaaa"}, {"value":"bbbb"}, {"value":"ccccc"}]}}
,但我不希望生成的JSON包含类的参数名称,并且仅包含param值。它应该简单地看起来像一个逗号分隔的值 [" aaaaa"," bbbb"," ccccc"]
之类的东西 {"genre":{"name":"xxxxxx","types":["aaaaa","bbbb","ccccc"]}}
有什么办法,使用杰克逊序列化一组具有简单值但不是参数名称的类?
我的映射器看起来像这个
private val mapper = new ObjectMapper
mapper.registerModule(DefaultScalaModule)
预先感谢!
它应该看起来像一个逗号分离的值[" aaaaa"," bbbb"," ccccc"]
那是 Set[String]
,但您拥有的是Set[Type]
。杰克逊正在做应该做的事情。您需要将班级签名更改为:
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])
输出:
Genre: {"name":"xxxxxx","types":[{"value":"aaaaa"},{"value":"bbbb"},{"value":"ccccc"}]}
AnotherGenre: {"name":"xxxxxx","types":["aaaaa","bbbb","ccccc"]}