yuval
unread,Mar 27, 2011, 10:14:57 AM3/27/11Sign in to reply to author
Sign in to forward
You do not have permission to delete messages in this group
Sign in to report message
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to google-gson
Hi
I want to gson and de-gson a hashmap with generics.
I can do it successfully when my key is a string but not if it is an
object.
I have the two code part here . the first doesnt work and the second
does.
First throws an
I implemented the
// doesnt work works - with string
try {
TradableBean tradable = new TradableBean("Tradable");
PositionBean position = new PositionBean(tradable);
Map<TradableBean, PositionBean> map1 = new
HashMap<TradableBean, PositionBean>();
map1.put(tradable, position);
String json1 = gson.toJson(map1);
Map<TradableBean, PositionBean> map2 =
gson.fromJson(json1, new TypeToken<Map<TradableBean, PositionBean>>()
{}.getType());
System.out.println(map2);
} catch (Exception e) {
System.out.println("failed");
}
// works - with string
try {
String tradable = new String("Tradable");
PositionBean position = new PositionBean(new
TradableBean("Tradable"));
Map<String, PositionBean> map1 = new HashMap<String,
PositionBean>();
map1.put(tradable, position);
String json1 = gson.toJson(map1);
Map<String, PositionBean> map2 = gson.fromJson(json1, new
TypeToken<Map<String, PositionBean>>() {}.getType());
System.out.println(map2);
} catch (Exception e) {
System.out.println("failed");
}
and in the TradableBean I have :
@Override public int hashCode() {
return getId();
}
@Override public boolean equals(Object obj) {
boolean equals = false;
if (obj instanceof AccountBean){
TradableBean tradable_p = (TradableBean)obj;
if (getId()==tradable_p.getId()){
equals = true;
}
}
return equals;
}
the exception
com.google.gson.JsonParseException: Expecting object found:
"TradableBean{id=0, tradableName='Tradable', moneyMultiplier=1,
expirationDate=null}"
at
com.google.gson.JsonObjectDeserializationVisitor.visitFieldUsingCustomHandler(JsonObjectDeserializationVisitor.java:
100)
at
com.google.gson.ObjectNavigator.navigateClassFields(ObjectNavigator.java:
150)
at com.google.gson.ObjectNavigator.accept(ObjectNavigator.java:123)
at
com.google.gson.JsonDeserializationContextDefault.fromJsonPrimitive(JsonDeserializationContextDefault.java:
84)
at
com.google.gson.JsonDeserializationContextDefault.deserialize(JsonDeserializationContextDefault.java:
53)
at com.google.gson.DefaultTypeAdapters
$MapTypeAdapter.deserialize(DefaultTypeAdapters.java:531)
at com.google.gson.DefaultTypeAdapters
$MapTypeAdapter.deserialize(DefaultTypeAdapters.java:498)
at
com.google.gson.JsonDeserializerExceptionWrapper.deserialize(JsonDeserializerExceptionWrapper.java:
50)
thank you.