在scala中,我试图将json转换回case类,但json有时包含空字符串。在这种情况下,它抛出:
com.fasterxml.jackson.databind.JsonMappingException: Instantiation of [simple type, class Person] value failed: null
at com.fasterxml.jackson.databind.deser.std.StdValueInstantiator.wrapException(StdValueInstantiator.java:399)
at com.fasterxml.jackson.databind.deser.std.StdValueInstantiator.createFromObjectWith(StdValueInstantiator.java:231)
at com.fasterxml.jackson.databind.deser.impl.PropertyBasedCreator.build(PropertyBasedCreator.java:135)
at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeUsingPropertyBased(BeanDeserializer.java:442)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromObjectUsingNonDefault(BeanDeserializerBase.java:1099)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:296)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:133)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3736)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2726)
at JacksonUtil$.fromJson(<console>:142)
... 58 elided
Caused by: java.lang.NullPointerException
... 66 more
我的转换器:
object JacksonUtil {
private var mapper = new ObjectMapper() with ScalaObjectMapper
intializeMapper( )
def intializeMapper() = {
// jackson library does not support seralization and deserialization of
// of scala classes like List and Map, this is needed to support it
mapper.registerModule( DefaultScalaModule )
// enables parsing of NaN. Enabling it here as JsonUtil class currently in
// use supports it.
mapper.configure(JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS, true )
mapper.setSerializationInclusion(Include.NON_NULL)
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
mapper.setSerializationInclusion(Include.NON_EMPTY)
mapper.setSerializationInclusion(Include.NON_ABSENT)
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)
}
def fromJson(json: String, clazz: Class[_]) = {
try {
mapper.readValue( json, clazz )
} catch {
case e: com.fasterxml.jackson.core.JsonParseException => {
println("Error while parsing JSON " + json)
}
}
}
}
有人可以告诉我这里做错了吗?
case class Person(itemId: Map[String, Int], itemNames: Map[String, Int]) extends Serializable
val test = """{}"""
JacksonUtil.fromJson(test, classOf[Person])
我应该添加任何配置吗?由于某些限制,我无法更改杰克逊映射器。
我在尝试使用适当的例外时也会遇到同样的异常:
val test1 = """{"itemId": {"A": 1,"B": 8},"itemNames": {"AMC" : 2, "Regal" : 5}"""
JacksonUtil.fromJson(test1, classOf[Person])