I want to make gson able to return an EnumMap
object. I use the following code
package sandbox;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.EnumMap;
import java.util.Map;
/**
*
* @author yccheok
*/
public class Sandbox {
public static void main(String[] args) throws InterruptedException {
testGson();
}
public static enum Country {
Malaysia,
UnitedStates
}
public static void testGson() {
Map<Country, String> enumMap = new EnumMap<Country, String>(Country.class);
enumMap.put(Country.Malaysia, "RM");
enumMap.put(Country.UnitedStates, "USD");
Gson gson = new Gson();
String string = gson.toJson(enumMap);
System.out.println("toJSon : " + string);
enumMap = gson.fromJson(string, new TypeToken<EnumMap<Country, String>>(){}.getType());
System.out.println("fromJSon : " + enumMap);
System.out.println("fromJSon : " + enumMap.getClass());
}
}
However, I'm getting the following
toJSon : {"Malaysia":"RM","UnitedStates":"USD"}
fromJSon : {Malaysia=RM, UnitedStates=USD}
fromJSon : class java.util.LinkedHashMap
even though I had used new TypeToken<EnumMap<Country, String>>(){}.getType()
to specific I want EnumMap
instead of LinkedHashMap
How can I make gson to return EnumMap
?