我有一个如下所示的 Spring 启动应用程序,它在响应正文中使用空 JSON“{}”响应查询。
根据我的理解,@RestController 应该自动处理对象到 JSON 的编码
我哪里错了?
我的请求:http://localhost:8080/name/sdhf
响应是:-
状态: 200 OK 显示说明加载时间:353
请求 header
用户代理:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36 来源:chrome-extension://hgmloofddffdnphfgcellkdfbfbjeloo 内容类型:application/json 接受:/ DNT:1 接受编码:gzip、deflate 接受语言:en-US,en;q=0.8
响应头
服务器:Apache-Coyote/1.1 内容类型:application/json;charset=UTF-8 传输编码:分块 日期:2015 年 2 月 22 日,星期日,格林威治标准时间 21:44:15
响应主体:
{}
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")
}
版主.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
用 BeanProperty 上课注解。我更喜欢这里的案例类,但您使用的是常规类,应该没问题。所以每个字段都是这样的:
@BeanProperty
var name ="jdgsjdhg"
选项 2
使用案例类并向对象映射器注册 Jackson Scala 模块。参见 here .这对我来说似乎是更好的选择,但需要预先进行一些额外的设置。
关于json - 如果类的对象是 Rest Controller ,如何确保它由 Spring boot 自动编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28663693/