GSON - 反序列化 java 泛型集合
我正在尝试从数据库反序列化数组列表,但没有成功。
这是我放置对象的方式:
for (int i = 0; i < dealsList.size(); i++) {
ServerServicesInternalWrapper.reportDeal(Json.toWrap(dealsList.get(i)));
}
这
public static <T> String toWrap(T t) {
JsonWrapperWithType wrapper =
new JsonWrapperWithType(t.getClass(),gson.toJson(t));
return to(wrapper);
}
是我选择的方式
return (List<DealBean>)session.createCriteria(DealBean.class).add(Restrictions.eq("portfolio", portfolio)).list();
,然后我使用 Gson 将其转换为字符串
JsonWrapperWithType wrapper =
new JsonWrapperWithType(t.getClass(), gson.toJson(t));
return gson.toJson(wrapper );
,这就是我 de-gson 对象的方式
而现在——例外
Type listType = new TypeToken<List<DealBean>>(){}.getType();
List<DealBean> dealsForPortfolio =
(List<DealBean>)gson.fromJson(dealsForPortfolioString,type);
com.google.gson.JsonParseException: The JsonDeserializer
com.google.gson.DefaultTypeAdapters$CollectionTypeAdapter@1f899e9 failed to deserialized
json object {"type":"java.util.ArrayList","content":"[{\"ID\":5,\"tradable\":
...
Caused by: java.lang.IllegalStateException: This is not a JSON Array.
I am trying to deserialize an arraylist from the DB withiout a success.
this is the way I put my objects:
for (int i = 0; i < dealsList.size(); i++) {
ServerServicesInternalWrapper.reportDeal(Json.toWrap(dealsList.get(i)));
}
where
public static <T> String toWrap(T t) {
JsonWrapperWithType wrapper =
new JsonWrapperWithType(t.getClass(),gson.toJson(t));
return to(wrapper);
}
this is the way I select
return (List<DealBean>)session.createCriteria(DealBean.class).add(Restrictions.eq("portfolio", portfolio)).list();
and then I Gson it to a string using
JsonWrapperWithType wrapper =
new JsonWrapperWithType(t.getClass(), gson.toJson(t));
return gson.toJson(wrapper );
and this is the way I de-gson the object
And now - the exception
Type listType = new TypeToken<List<DealBean>>(){}.getType();
List<DealBean> dealsForPortfolio =
(List<DealBean>)gson.fromJson(dealsForPortfolioString,type);
com.google.gson.JsonParseException: The JsonDeserializer
com.google.gson.DefaultTypeAdapters$CollectionTypeAdapter@1f899e9 failed to deserialized
json object {"type":"java.util.ArrayList","content":"[{\"ID\":5,\"tradable\":
...
Caused by: java.lang.IllegalStateException: This is not a JSON Array.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Gson 需要一个 Json 对象列表,例如:
[{obj1}, {obj2}, ... , {objN}]
我不确定您在此处发布的代码的意图是什么,但似乎对我来说就像你正在用父对象包装一个列表。
如果您想要这样的情况,您需要制作自己的 解串器。
Gson expects a list of Json objects like:
[{obj1}, {obj2}, ... , {objN}]
I'm not sure from code you posted here what your intentions were but it seems to me like you are wrapping a list with parent object.
In the case you want it like that, you need to make your own deserializer.