简体   繁体   中英

Get Gson Key's Name In An Overriden Adapter

I have overriden an Integer Adapter in GSON to parse my JSON. Reason for doing this is that the GSON method parseJson simply throws the JsonSyntaxException if anything goes wrong. 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. Problem is that I can not get the key name in the overriden method deserialize of JsonDeserializer[T]

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 }

Any leads on this?

Your adapter is a deserializer for the Integer type which is a wrapper for a primitive. Because it's not a regular object, Gson will not associate a key with it.

Why not implement a deserializer for the whole JSON object to have access to all keys?

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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