我已经覆盖了 GSON 中的整数适配器来解析我的 JSON。这样做的原因是,如果出现任何问题,GSON 方法parseJson
简单地抛出JsonSyntaxException
。为了避免发送通用异常,我创建了此适配器。我希望适配器抛出异常以及密钥的名称。问题是我无法在覆盖的方法deserialize
中获取键名JsonDeserializer[T]
代码片段
val integerAdapter = new JsonDeserializer[Integer] {
override def deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): Integer = {
Try(json.getAsInt) //JsonElement object has only the value
match {
case Success(value) => value
case Failure(ex) => throw new IllegalArgumentException(ex) // here i want the name of the key to be thrown in the exception and manage accordingly
}
}
}
杰森:{
"supplierId":"21312",
"isClose":false,
"currency":"USD",
"statusKey":1001,
"statusValue":"Opened ",
"statusDateTime":"2014-03-10T18:46:40.000Z",
"productKey":2001,
"productValue":"Trip Cancellation",
"TypeKey":3001,
"TypeValue":"Trip Cancellation",
"SubmitChannelKey":4001,
"SubmitChannelValue":"Web asdsad",
"tripNumber":"01239231912",
"ExpiryDateTime":"2014-03-10T18:46:40.000Z",
"numberOfants":4,
"AmountReserved":901232,
"AmountRequested":91232
}
有什么线索吗?
您的适配器是 Integer 类型的反序列化程序,它是基元的包装器。因为它不是常规对象,所以 Gson 不会将键与它关联。
为什么不为整个 JSON 对象实现反序列化程序以访问所有键?
class MyObject {
private Integer supplierId;
private boolean isClose;
// TODO: the other fields in the JSON string
}
class MyObjectDeserializer implements JsonDeserializer<MyObject> {
public MyObject deserialize(JsonElement jsonElement, Type type,
JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
// TODO: construct a new MyObject instance
}
}