【问题标题】:Serialisation of Java and Scala objects with Scalatra使用 Scalatra 序列化 Java 和 Scala 对象
【发布时间】:2016-06-06 16:34:13
【问题描述】:

我继承了一个提供 REST API 的旧版 Scalatra 应用程序。如果返回的对象是基于其他案例类的案例类,则返回对象的序列化可以完美地工作。但是如果返回一个从 Java 或 Scala 类创建的对象,它不会被 Scalatra 序列化。我只会得到 Object.toString() 的结果。那么我还需要正确地序列化非案例类吗?

这是我的课

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"))
  }
}

【问题讨论】:

    标签: scala scalatra json4s


    【解决方案1】:

    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 文档中的示例,修改后显示了一个工作 servlet 从常规类返回序列化 json。

    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]()
    
    }
    

    【讨论】:

      猜你喜欢
      • 2019-06-11
      • 2015-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-02
      • 1970-01-01
      • 2014-08-18
      • 1970-01-01
      相关资源
      最近更新 更多