我有两个JSON格式(example_json1,example_json2)和一个使用Scala解析JSON的简单类地址。我可以使用字段类型String或StringWrapper获得JSON。
我怎么能把它们概括起来?
现在,这段代码可以将唯一的"example_json1“转换为Address对象。
object AdressJson {
val example_json1 =
"""{
"value":
{
"string":"MY ADDRESS"
}
}"""
val example_json2 =
"""{
"value":"STREET"
}"""
}
object Main {
val mapper = new ObjectMapper() with ScalaObjectMapper
mapper.registerModule(DefaultScalaModule)
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
def main(args: Array[String]): Unit = {
val parsedJson = mapper.readValue(AdressJson.example_json1, classOf[Address])
println(parsedJson)
}
}
case class Address(value: StringWrapper)
case class StringWrapper(string: String)我希望这样的代码能够同时使用这两种类型(甚至更多的类型)。
--我可以为它创建通用代码,而不必像instanceOf那样使用instanceOf吗?Scala中解决这个问题的方法是什么?我可以为它创建反序列化器吗?
发布于 2019-01-29 19:44:13
我的解决方案:
case class Address(@JsonDeserialize(using = classOf[AdminStatusDesializer])
value: StringWrapper)
class AdminStatusDesializer extends JsonDeserializer[StringWrapper]{
override def deserialize(p: JsonParser, ctxt: DeserializationContext): StringWrapper = {
val oc = p.getCodec()
val node:JsonNode = oc.readTree(p)
if(node.isNull)StringWrapper(null)
if(node.isTextual) StringWrapper(node.asText())
else StringWrapper(node.get("string").asText())
}
}https://stackoverflow.com/questions/54408892
复制相似问题