如何使用Scalatra制作默认响应Content-type:application / json

问题描述 投票:3回答:1

我正在学习Scalatra,我想知道如何制作我的回复application/json的默认内容类型。目前的默认值似乎是text/html。整洁,但对我的应用程序并不真正有用。

目前的默认值是text/html

$ curl -i -X GET 'http://localhost:8080/v1/example'
HTTP/1.1 200 OK
Date: Fri, 19 Apr 2019 07:21:21 GMT
Content-Type: text/html;charset=utf-8
Content-Length: 23
Server: Jetty(9.4.8.v20171121)

HelloWorld(hello,world)

我可以通过application-json标题明确地获得Accepted: application/json

$ curl -i -X GET 'http://localhost:8080/v1/example' -H 'Accept: application/json'
HTTP/1.1 200 OK
Date: Fri, 19 Apr 2019 07:22:09 GMT
Content-Type: application/json;charset=utf-8
Transfer-Encoding: chunked
Server: Jetty(9.4.8.v20171121)

{"hello":"hello","world":"world"}

如何将默认值设置为application/json

scala scalatra
1个回答
3
投票

可以覆盖defaultFormat以使application/json成为默认情况。例如,

import java.io.File
import org.scalatra._
import org.scalatra.util.MimeTypes
import org.json4s.{DefaultFormats, Formats}
import org.scalatra.json._

case class HelloWorld(hello: String, world: String)

class MyScalatraServlet extends ScalatraServlet with JacksonJsonSupport {
  protected implicit lazy val jsonFormats: Formats = DefaultFormats

  override def defaultFormat: Symbol = 'json

  get("/v1/example") {
    HelloWorld("hello", "world")
  }

}

没有指定Accept标题应该回应

curl -i -X GET 'http://localhost:8080/v1/example'
HTTP/1.1 200 OK
Date: Thu, 25 Apr 2019 22:28:37 GMT
Content-Type: application/json;charset=utf-8
Content-Length: 33
Server: Jetty(9.4.8.v20171121)

{"hello":"hello","world":"world"}

虽然明确要求Accept: text/html也有效

curl -i -X GET 'http://localhost:8080/v1/example' -H 'Accept: text/html'
HTTP/1.1 200 OK
Date: Fri, 26 Apr 2019 15:45:22 GMT
Content-Type: text/html;charset=utf-8
Content-Length: 23
Server: Jetty(9.4.8.v20171121)

HelloWorld(hello,world)
© www.soinside.com 2019 - 2024. All rights reserved.