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.
// doesnt work works
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");
}
and now the working part –
// 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)
I think you need to write your own custom serializator.
Update: the tell-tale is the exception:
The prepending string “TradableBean” seems to be written by a serialization that uses some sort of
toString(). the Deserialization expected an object of the form{id=0,... }