gson:从Json参数化取决于类型 [英] gson: parametrized fromJson depending on the Type

查看:126
本文介绍了gson:从Json参数化取决于类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起,这肯定已经问了,但我没有找到我需要的

我有几种消息类型:

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

以及从json邮件中解码它们的方法:

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

然后例如:

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

可以工作,但是很丑,我如何可以有一个参数化的getMessage函数,和铸造

thx

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

推荐答案

添加< T> 到方法签名,紧接在返回类型之前。这将创建一个类型参数化方法:

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

这样调用:

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

这篇关于gson:从Json参数化取决于类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆