我继承了一个遗留的Scalatra应用程序,它提供了REST。如果返回的对象是在其他案例类的基础上构建的case类,则返回对象的序列化工作得很好。但是,如果返回从Java或Scala类创建的对象,则Scalatra不会序列化对象。我只会得到Object.toString()的结果。那么,我需要做什么来正确地序列化非case类?
这是我的班
class Snafu(sna: String, foo: String) {
}这是我的servlet:
class HealthServlet(implicit inj: Injector)
extends ScalatraServlet with SLF4JLogging
with JacksonJsonSupport
with Injectable with InternalViaLocalhostOnlySupport {
protected implicit val jsonFormats: Formats = DefaultFormats
val healthStateCheck = inject[HealthStateCheck]
before("/") {
}
get("/") {
Ok(new Snafu("4", "2"))
}
}发布于 2016-07-03 18:24:22
在json4s中,默认情况下不支持非case类序列化。您需要为类添加一个CustomSerializer。
class IntervalSerializer extends CustomSerializer[Interval](format => (
{
// Deserialize
case JObject(JField("start", JInt(s)) :: JField("end", JInt(e)) :: Nil) =>
new Interval(s.longValue, e.longValue)
},
{
// Serialize
case x: Interval =>
JObject(JField("start", JInt(BigInt(x.startTime))) ::
JField("end", JInt(BigInt(x.endTime))) :: Nil)
}
))您还需要将这些序列化程序添加到正在使用的jsonFormats中。
protected implicit lazy val jsonFormats: Formats = DefaultFormats + FieldSerializer[Interval]()下面是修改后的json4s文档中的示例,以显示从常规类返回序列化json的工作servlet。
import org.json4s._
import org.json4s.JsonAST.{JInt, JField, JObject}
import org.scalatra.json.JacksonJsonSupport
class Interval(start: Long, end: Long) {
val startTime = start
val endTime = end
}
class IntervalSerializer extends CustomSerializer[Interval](format => (
{
// Deserialize
case JObject(JField("start", JInt(s)) :: JField("end", JInt(e)) :: Nil) =>
new Interval(s.longValue, e.longValue)
},
{
// Serialize
case x: Interval =>
JObject(JField("start", JInt(BigInt(x.startTime))) ::
JField("end", JInt(BigInt(x.endTime))) :: Nil)
}
))
class IntervalServlet extends ScalatraServlet with ScalateSupport with JacksonJsonSupport {
get("/intervalsample") {
contentType = "application/json"
val interval = new Interval(1, 2)
Extraction.decompose(interval)
}
protected implicit lazy val jsonFormats: Formats = DefaultFormats + FieldSerializer[Interval]()
}https://stackoverflow.com/questions/37662586
复制相似问题