user1125394
user1125394

Reputation:

gson: parametrized fromJson depending on the Type

I'm sorry it was surely already asked, but I did not find what I need
I have several message types:

class AbstractMessage {
    int code;
    String token;
}

class ShareMessage extends AbstractMessage{
    String user;
    Map<String, String> friends;
}

class PostMessage extends AbstractMessage{
    String user;
    Map<String, String> data;
}

and a method to decode them from the json post message:

public Object getMessage(BufferedReader r, Type t){
    Object o = null;
    try{
        o = g.fromJson(r, t);
    } catch (final JsonSyntaxException e) {
        LOGGER.info("Error in Json format", e);
    } catch (final JsonParseException e) {
        LOGGER.info("Error in parsing Json", e);
    }

    return o;
}

then for example:

Type dataType = new TypeToken<PostMessage>() {}.getType();
PostMessage m = (PostMessage) getMessage(request.getReader(), dataType);

works, but it's ugly, how can I have a parametrized getMessage function, or anything better than returning Object and casting
thx

Upvotes: 1

Views: 719

Answers (1)

Jesse Wilson
Jesse Wilson

Reputation: 40613

Add <T> to the method signature, immediately before the return type. This creates a type-parameterized method:

public <T> T getMessage(BufferedReader r, TypeToken<T> typeToken){
  try {
    return g.fromJson(r, typeToken.getType());
  } catch (final JsonSyntaxException e) {
    LOGGER.info("Error in Json format", e);
  } catch (final JsonParseException e) {
    LOGGER.info("Error in parsing Json", e);
  }
  return null;
}

Call it like this:

PostMessage m = getMessage(request.getReader(), new TypeToken<PostMessage>() {});

Upvotes: 1

Related Questions