如果它是 Rest 控制器,如何确保 class 的 object 由 Spring 引导自动编组

How to make sure that an object of a class is marshalled automatically by Spring boot if it is a Rest controller

我有一个 Spring 启动应用程序,它在响应的 body 中用空的 JSON“{}”响应查询。

根据我的理解,@RestController 应该自动处理 objects 到 JSON

的编组

我哪里错了?

我的要求:http://localhost:8080/name/sdhf

响应是:-

状态: 200 OK 显示说明加载时间:353

请求headers

User-Agent:Mozilla/5.0(Macintosh;英特尔 Mac OS X 10_10_2)AppleWebKit/537。 36(KHTML,如 Gecko)Chrome/40.0.2214.115 Safari/537.36 来源:chrome-extension://hgmloofddffdnphfgcellkdfbfbjeloo Content-Type: application/json 接受:/ DNT:1 Accept-Encoding: gzip, deflate Accept-Language: en-US,en;q=0.8

回复headers

服务器:Apache-Coyote/1.1 Content-Type: application/json;字符集=UTF-8 Transfer-Encoding:分块 日期:2015 年 2 月 22 日,星期日 21:44:15 GMT

响应正文:

{}

HelloWebAplication.scala

package helloKW
import org.springframework.http.converter.json
import org.springframework.boot.autoconfigure.EnableAutoConfiguration
import org.springframework.boot.SpringApplication
import org.springframework.web.bind.annotation.{RequestMapping, RestController}
/**
 * This object bootstraps Spring Boot web application.
 * Via Gradle: gradle bootRun
 *
 */
 @EnableAutoConfiguration
object HelloWebApplication {

    def main(args: Array[String]) {
       SpringApplication.run(classOf[AxyzConfig]);
    }
}

AxyzConfig.scala

package helloKW


import org.springframework.boot.autoconfigure.EnableAutoConfiguration
import org.springframework.context.annotation.{ComponentScan, Configuration}
import org.springframework.http.{HttpStatus, ResponseEntity}
import org.springframework.web.bind.annotation._
import org.springframework._

/**
 * This config class will trigger Spring @annotation scanning and auto configure Spring context.
 *
 *     
 */
@RestController
@Configuration
@EnableAutoConfiguration
@ComponentScan
class AxyzConfig {
  var m : Moderator = new Moderator(10,"shgd","fsd","ifge")
  var x =10

  @RequestMapping(method = Array {RequestMethod.POST},value=Array{"/name/{name}"})
  @ResponseBody
  def returnParamName(@PathVariable name:String) = new Moderator(45,"sjfg","ksgfs","kurreuk")

}

Moderator.scala

package helloKW


class Moderator (){
  var id = 10
  var name ="jdgsjdhg"
  var email ="sdkgsd"
  var password ="sdkfjhsdfk"

  def this(a:Int,b:String,c:String,d:String){
    this()
    this.id =  a
    this.email = b
    this.name = c
    this.password = d
  }


}

如果您使用 Jackson 作为您的默认序列化器,那么 Moderator 应该是一个带有 getter 和 setter 的 java bean。由于没有 getter 和 setter,因此对象为空。

您有两个主要选择。

选项 1
Class 带有 BeanProperty 注释。我更喜欢这里的 case class 但你使用的是常规 class 应该没问题。所以每个字段都是这样的:

@BeanProperty
var name ="jdgsjdhg"

选项 2
使用 Case Classes 并使用对象映射器注册 Jackson Scala 模块。参见 here。这对我来说似乎是更好的选择,但需要预先进行一些额外的设置。