简体   繁体   English

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

[英]Get Gson Key's Name In An Overriden Adapter

I have overriden an Integer Adapter in GSON to parse my JSON. 我已经在GSON中覆盖了一个整数适配器来解析我的JSON。 Reason for doing this is that the GSON method parseJson simply throws the JsonSyntaxException if anything goes wrong. 这样做的原因是,如果发生任何错误,GSON方法parseJson只会抛出JsonSyntaxException To avoid sending a generic exception I created this adapter. 为了避免发送通用异常,我创建了此适配器。 I want the adapter to throw an exception along with the name of the Key. 我希望适配器将异常与Key的名称一起引发。 Problem is that I can not get the key name in the overriden method deserialize of JsonDeserializer[T] 问题是我无法在JsonDeserializer[T] deserialize化的重写方法中获得键名。

Code snippet 程式码片段

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

Any leads on this? 有什么线索吗?

Your adapter is a deserializer for the Integer type which is a wrapper for a primitive. 您的适配器是Integer类型的反序列化器,它是基元的包装器。 Because it's not a regular object, Gson will not associate a key with it. 因为它不是常规对象,所以Gson不会将密钥与其关联。

Why not implement a deserializer for the whole JSON object to have access to all keys? 为什么不为整个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
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM