在Overriden适配器中获取Gson Key的名称

时间:2017-06-23 06:22:03

标签: java json scala gson

我在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

  }
 }
}

JSON:{ "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 }

这方面的任何线索?

1 个答案:

答案 0 :(得分:0)

您的适配器是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
    }
}