我想让 gson 能够返回一个EnumMap
对象。我使用以下代码
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());
}
}
但是,我得到以下
toJSon : {"Malaysia":"RM","UnitedStates":"USD"}
fromJSon : {Malaysia=RM, UnitedStates=USD}
fromJSon : class java.util.LinkedHashMap
即使我已经习惯于new TypeToken<EnumMap<Country, String>>(){}.getType()
具体我想要EnumMap
而不是LinkedHashMap
我怎样才能让 gson 返回EnumMap
?