Open GoogleCodeExporter opened 9 years ago
I am new with Gson, but I managed to do this with a custom serializer and
deserializer. Nevertheless, I still think this should be implemented without
needing them:
GsonBuilder gb = new GsonBuilder();
Type t = (new TypeToken<Map<Test, Integer>>(){}).getType();
gb.registerTypeAdapter(t, new JsonSerializer<Map<Test,Integer>>(){
@Override
public JsonElement serialize(Map<Test, Integer> arg0, Type arg1, JsonSerializationContext arg2) {
// TODO Auto-generated method stub
JsonObject obj = new JsonObject();
for (Test t : arg0.keySet()) {
obj.add(arg2.serialize(t).getAsString(), new JsonPrimitive(arg0.get(t)));
}
return obj;
}
});
gb.registerTypeAdapter(t, new JsonDeserializer<Map<Test,Integer>>(){
@Override
public Map<Test, Integer> deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
Map<Test, Integer> res = new EnumMap<Test, Integer>(Test.class);
Entry<String, JsonElement> entry;
Test tVal;
Iterator<Entry<String,JsonElement>> it = arg0.getAsJsonObject().entrySet().iterator();
while (it.hasNext()) {
entry = it.next();
tVal = arg2.deserialize(new JsonPrimitive(entry.getKey()), Test.class);
res.put(tVal, entry.getValue().getAsInt());
}
return res;
}
});
Gson gson = gb.create();
Map<Test, Integer> testMap = new EnumMap<Test, Integer>(Test.class);
testMap.put(Test.A, 3);
testMap.put(Test.B, 2);
testMap.put(Test.C, 1);
System.out.println(gson.toJson(testMap, t));
testMap = gson.fromJson(gson.toJson(testMap, t), t);
System.out.println(testMap.get(Test.A));
System.out.println(testMap.get(Test.B));
System.out.println(testMap.get(Test.C));
The output now is:
{"aaa":3,"bbb":2,"ccc":1}
3
2
1
Original comment by FernA...@gmail.com
on 22 Sep 2012 at 4:34
I am encountering similar issue, I am using Gson on android.
public enum Mode {
@SerializedName("no_account_creation")
LOGIN,
@SerializedName("force_account_creation")
REGISTER,
@SerializedName("auto")
AUTO;
}
On 2.3.6 and above:
Mode.AUTO serializes to "auto"
On HTC explorer 2.3.5
Mode.AUTO serializes to "AUTO"
Is it possible that the fix of
https://code.google.com/p/google-gson/issues/detail?id=347
be somehow depended on the version of dvm?
Original comment by Platinum...@gmail.com
on 18 Mar 2013 at 9:51
Original issue reported on code.google.com by
FernA...@gmail.com
on 22 Sep 2012 at 2:11