如果我有一个JSON对象,比如:
{
"test": 3
}然后,我预计将"test“字段提取为字符串将会失败,因为类型没有对齐:
import org.json4s._
import org.json4s.jackson.JsonMethods
import org.json4s.JsonAST.JValue
def getVal[T: Manifest](json: JValue, fieldName: String): Option[T] = {
val field = json findField {
case JField(name, _) if name == fieldName => true
case _ => false
}
field.map {
case (_, value) => value.extract[T]
}
}
val json = JsonMethods.parse("""{"test":3}""")
val value: Option[String] = getVal[String](json, "test") // Was Some(3) but expected None在Json4s中,从JSON数字到字符串的自动转换是预期的吗?如果是这样的话,是否有任何解决方法,其中提取的字段必须与extract方法的类型参数中指定的类型相同?
发布于 2017-02-03 08:40:12
这是大多数解析器(如果不是所有解析器)的默认特性。如果您请求一个类型为T的值,并且该值可以安全地转换为该特定类型,则库将为您转换它。例如,看一下类型安全配置,它的性质类似于将数值字段转换为字符串。
import com.typesafe.config._
val config = ConfigFactory parseString """{ test = 3 }"""
val res1 = config.getString("test")
res1: String = 3如果您不想自动将Integer/Boolean转换为String,您可以手动检查Int/Boolean类型,如下所示。
if(Try(value.extract[Int]).isFailure || Try(value.extract[Boolean]).isFailure) {
throw RuntimeException(s"not a String field. try Int or Boolean")
} else {
value.extract[T]
}发布于 2020-05-29 21:04:41
一种简单的解决方法是为您需要“严格”行为的情况创建自定义序列化程序。例如:
import org.json4s._
val stringSerializer = new CustomSerializer[String](_ => (
{
case JString(s) => s
case JNull => null
case x => throw new MappingException("Can't convert %s to String." format x)
},
{
case s: String => JString(s)
}
))将此序列化程序添加到隐式格式可确保严格的行为:
implicit val formats = DefaultFormats + stringSerializer
val js = JInt(123)
val str = js.extract[String] // throws MappingExceptionhttps://stackoverflow.com/questions/42010763
复制相似问题