列表到Json数组InvocationTargetException

时间:2015-05-26 16:36:09

标签: java mysql json jpa

我有一个包含优惠的util.List。类提供的变量是:

Integer id, Date startDate, Date endDate, String offerMessage, String creationDate, String updateDate.

我使用NetBeans从MySQL数据库生成了JPA实体和Controller,我在数据库中设置了startDate,endDate作为Timestamp。

正如您所看到的,实体中的注释是:

@Basic(optional = false)
@Column(name = "startDate")
@Temporal(TemporalType.TIMESTAMP)
private Date startDate;

@Basic(optional = false)
@Column(name = "endDate")
@Temporal(TemporalType.TIMESTAMP)
private Date endDate;

当我测试我的轴webservice时,我做了类似的事情:

WebService中的

reply = _protocol.reply(request);

并在议定书中:

public String reply(String request) throws Exception {
    String reply = "I dont understand you!";
    try {
        if (request.equals("a")) {
            OfferJpaController oferJpaController = new OfferJpaController();
            List<Offer> allOffers = oferJpaController.findOfferEntities();
            Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new DateTypeAdapter() ).create();
            reply = gson.toJson(allOffers);
        }
    } catch (Exception ex) {
            throw ex;
    }
    return reply;
}

我得到异常:java.lang.reflect.InvocationTargetException消息:java.lang.reflect.InvocationTargetException

我可以想象,问题是util.Date,我在这里搜索其他问题,但我没有设法解决这个问题。我该怎么办?也许将时间戳字段存储为db中的整数,并为数据库转换进行事后操作?

1 个答案:

答案 0 :(得分:1)

私有静态类DateTimeTypeConverter       实现JsonSerializer,JsonDeserializer {

@Override
public JsonElement serialize(DateTime src, Type srcType, JsonSerializationContext context) {
  return new JsonPrimitive(src.toString());
}

@Override
public DateTime deserialize(JsonElement json, Type type, JsonDeserializationContext context)
    throws JsonParseException {
  try {
    return new DateTime(json.getAsString());
  } catch (IllegalArgumentException e) {
    // May be it came in formatted as a java.util.Date, so try that
    Date date = context.deserialize(json, Date.class);
    return new DateTime(date);
  }
}

}