首页 > 解决方案 > ObjectMapper readValue(content: String) 如果字符串在 Scala 中为空“”,则给出 MismatchedInputException

问题描述

使用 Jackson ObjectMapper 转换响应时。如果响应正文为空字符串,则获取 com.fasterxml.jackson.databind.exc.MismatchedInputException:由于 [Source: (String)"" 处的输入结束,没有要映射的内容;行:1,列:0] 而 mapper.readValue(response)

在 Scala 中,从发布请求中获取空响应“”并尝试通过 ObjectMapper 解析它。

来自 ObjectMapper:

def readValue[T: Manifest](content: String): T = {
 readValue(content, constructType[T])
}

像这样调用:

val m = new ObjectMapper() with ScalaObjectMapper
m.readValue[String](httpresponse.body) // httpresponse.body=""

出现以下错误:- com.fasterxml.jackson.databind.exc.MismatchedInputException:由于 [Source: (String)"" 处的输入结束,没有要映射的内容;行:1,列:0]

已经为映射器提供以下配置:-

m.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
m.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
m.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true)
m.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT)

标签: scalaobjectmapperis-empty

解决方案


推荐阅读