Scalatra JSON指南代码无法编译

时间:2013-06-17 20:05:48

标签: scala scalatra

我复制了JSON格式指南中的说明:http://www.scalatra.org/2.2/guides/formats/json.html

下面是MyScalatraServlet.scala文件,其中嵌入了所有代码以测试JSON格式:

package net.example.testapp

import org.scalatra._
import scalate.ScalateSupport

// JSON-related libraries
import org.json4s.{DefaultFormats, Formats}

// JSON handling support from Scalatra
import org.scalatra.json._

class MyScalatraServlet extends TestAppStack with JacksonJsonSupport {

  get("/") {
    FlowerData.all
  }

}

// Sets up automatic case class to JSON output serialization, required by
// the JValueResult trait.
protected implicit val jsonFormats: Formats = DefaultFormats

case class Flower(slug: String, name: String)

object FlowerData {

  /**
   * Some fake flowers data so we can simulate retrievals.
   */
  var all = List(
      Flower("yellow-tulip", "Yellow Tulip"),
      Flower("red-rose", "Red Rose"),
      Flower("black-rose", "Black Rose"))
}

似乎编译器不喜欢以下行:

protected implicit val jsonFormats: Formats = DefaultFormats

以下是错误消息:

[error] /Users/test/test-app/src/main/scala/net/example/testapp/MyScalatraServlet.scala:22: expected start of definition
[error] protected implicit val jsonFormats: Formats = DefaultFormats
[error]                    ^
[error] one error found
[error] (compile:compile) Compilation failed
[error] Total time: 2 s, completed Jun 17, 2013 4:04:34 PM
> 

1 个答案:

答案 0 :(得分:2)

你的val jsonFormats只是漂浮在那里,没有与班级或任何东西联系在一起。需要将val定义为另一个构造的一部分,如特征,类或对象。尝试在调用get("/")

之前将其移动到该servlet类中