【问题标题】:Scala with spring boot - issue with change json key带有spring boot的Scala-更改json键的问题
【发布时间】:2018-02-15 06:19:55
【问题描述】:

我有这门课

@JsonSerialize
case class TimeTableIndexItem(@BeanProperty @JsonProperty("name") var name: String,
                              @BeanProperty @JsonProperty("type") var category: String) extends Serializable {
  override def toString: String = {
    s"$name $category"
  }
}

我想将 json 键名从“类别”更改为“名称”我不知道为什么它不起作用?当我使用 java 时它也可以工作(@JsonProperty)

【问题讨论】:

    标签: json spring scala spring-boot


    【解决方案1】:

    添加

    libraryDependencies += "com.fasterxml.jackson.module" % "jackson-module-scala_2.12" % "2.9.0"
    

    构建.sbt。这个依赖不是 Spring Boot 添加的。

    那么下面的代码就起作用了:

    import com.fasterxml.jackson.databind.ObjectMapper
    import com.fasterxml.jackson.module.scala.DefaultScalaModule
    
    val objectMapper = new ObjectMapper
    objectMapper.registerModule(DefaultScalaModule)
    val item = TimeTableIndexItem("name1", "category1")
    val s = objectMapper.writeValueAsString(item)
    println(s)
    

    {"name":"name1","type":"category1"}

    基于answer


    您尚未注册该模块。修改你的 Spring Boot 配置:

    @Configuration
    @EnableAutoConfiguration
    @ComponentScan
    class SampleConfig {
      @Bean
      @Primary
      def objectMapper(): ObjectMapper = {
        val objectMapper = new ObjectMapper
        objectMapper.registerModule(DefaultScalaModule)
        objectMapper
      }
    }
    

    基于answer

    【讨论】:

    • 它不起作用。我的意思是当我使用 println(它是工作)但是当我在控制器中返回对象时,我得到的是类别而不是类型。 Ofc 我可以返回字符串,但我想返回 json。基本上是 TimeTableIndexItem 的列表。
    • github.com/stoton/zsat-timetable-backend 这是我的代码,没有这个改变你在说什么。看控制器
    • 是的,很抱歉没有重播
    猜你喜欢
    • 1970-01-01
    • 2018-12-19
    • 2020-11-25
    • 2020-02-22
    • 1970-01-01
    • 2021-12-21
    • 2021-12-30
    • 2015-10-19
    • 1970-01-01
    相关资源
    最近更新 更多