问题

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 enumMap = new EnumMap(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>(){}.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>(){}.getType() to specific I want EnumMap instead of LinkedHashMap

How can I make gson to return EnumMap?

回答1:

Even with a type token, Gson can only deserialize data into classes that have a default constructor. And EnumMap doesn't have one (it needs to be instantiated with the type of enum that its elements will match). The easiest way around this problem is to define and use an InstanceCreator:

This interface is implemented to create instances of a class that does not define a no-args constructor. If you can modify the class, you should instead add a private, or public no-args constructor. However, that is not possible for library classes, such as JDK classes, or a third-party library that you do not have source-code of. In such cases, you should define an instance creator for the class. Implementations of this interface should be registered with GsonBuilder.registerTypeAdapter(Type, Object) method before Gson will be able to use them.

Heres some example code:

InstanceCreator:

class EnumMapInstanceCreator, V> implements

InstanceCreator> {

private final Class enumClazz;

public EnumMapInstanceCreator(final Class enumClazz) {

super();

this.enumClazz = enumClazz;

}

@Override

public EnumMap createInstance(final Type type) {

return new EnumMap(enumClazz);

}

}

Test code:

final Gson gson = new GsonBuilder().registerTypeAdapter(

new TypeToken>() {

}.getType(),

new EnumMapInstanceCreator(Country.class))

.create();

final Map enumMap = new EnumMap(

Country.class);

enumMap.put(Country.Malaysia, "RM");

enumMap.put(Country.UnitedStates, "USD");

String string = gson.toJson(enumMap);

System.out.println("toJSon : " + string);

final Map reverseEnumMap = gson.fromJson(string,

new TypeToken>() {

}.getType());

System.out.println("fromJSon (Class): " + reverseEnumMap.getClass());

System.out.println("fromJSon : " + reverseEnumMap);

来源:https://stackoverflow.com/questions/16127904/gson-fromjson-return-linkedhashmap-instead-of-enummap

gson 获取hasmap_GSON fromJson return LinkedHashMap instead of EnumMap相关推荐

  1. (仿头条APP项目)4.父类BaseFragment创建,用retrofit和gson获取并解析服务器端数据

    文章目录 父类BaseFragment创建,用retrofit和gson获取并解析服务器端数据 效果展示 创建父类BaseFragment解决代码重复问题 用retrofit和gson获取并解析服务器 ...

  2. 关于ExecuteNonQuery执行存储过程的返回值 、、实例讲解存储过程的返回值与传出参数、、、C#获取存储过程的 Return返回值和Output输出参数值...

    关于ExecuteNonQuery执行存储过程的返回值 用到过ExecuteNonQuery()函数的朋友们在开发的时候肯定这么用过. if(cmd.ExecuteNonQuery("xxx ...

  3. C#获取存储过程的 Return返回值和Output输出参数值

    一.不用SQLHelper.cs等帮助类 1.获取Return返回值  程序代码  存储过程 Create PROCEDURE MYSQL   @a int,   @b int AS   return ...

  4. 获取axios的return值

    因axios返回值是异步操作,获取返回值时,请求操作还未完成,就已经执行了赋值,导致结果位undefined.错误示例如下: 1 2 3 4 5 6 7 8 9 10     function Get ...

  5. 用GSON 获取JSON数组属性

    /** * 解析有数据头的纯数组 */ private void parseHaveHeaderJArray() {     //拿到本地JSON 并转成String     String strBy ...

  6. vue怎么获取axios的return值?

    代码: methods:{getNum(){axios({url: '/api/blog',method: 'GET'}).then((res) => {return res})},getDat ...

  7. java gson fromjson,Gson的fromJson()方法

    Gson提供了fromJson()方法来实现从Json相关对象到java实体的方法. 在日常应用中,我们一般都会碰到两种情况,转成单一实体对象和转换成对象列表或者其他结构. 先来看第一种: 比如jso ...

  8. Gson的fromJson()方法

    Gson提供了fromJson()方法来实现从Json相关对象到Java实体的方法. 在日常应用中,我们一般都会碰到两种情况,转成单一实体对象和转换成对象列表或者其他结构. 先来看第一种: 比如jso ...

  9. 轻触开源(三)-Gson项目源码解析_贰

    2019独角兽企业重金招聘Python工程师标准>>> 转载请注明出处:https://my.oschina.net/u/874727/blog/750473 Q:102525062 ...

最新文章

  1. 你不会知道,一个小小电阻也很奇妙!
  2. c语言 方程改main的值_C语言编程笔记丨编写第一个C语言程序hello world,我教你哇...
  3. 不知道工作组名称怎样加入_第一次穿汉服不知道该怎样选择!一招教你用体型选汉服!...
  4. python3发送邮件_Python3 SMTP发送邮件
  5. CenOS7.4内核升级修复系统漏洞
  6. 两台服务器安装redis集群_两台服务器六节点redis集群环境搭建
  7. DRM-widevine 总结
  8. 万字详文阐释程序员修炼之道
  9. Javaweb常见面试题
  10. JAVA文件上传限制
  11. 如何制定项目里程碑?
  12. 【C++】1070:人口增长(信息学奥赛)
  13. 入侵html数据库,教你如何暴库(网站入侵)
  14. 微信小程序自定义地址选择器
  15. java报表是什么_什么是报表工具
  16. linux dp接口显示,DP接口无法输出2K甚至1080分辨率·「已解决」
  17. app打包上传遇到的问题
  18. 法坤老师:百度网盘密道转存12.0群文件自动转存发布咯
  19. Kubernetes容器编排引擎
  20. 【BBED】使用bbed 修改data block Block Misplaced

热门文章

  1. python读取配置文件-configparser
  2. Intelli IDEA+jdk++maven+tomcat环境配置
  3. 通过Intent传递类对象
  4. Codeforces Bubble Cup 8 - Finals [Online Mirror] B. Bribes lca
  5. 芈珺:iOS自动化测试工具总览
  6. SAX EntityResolver 的作用
  7. 写一段最短的代码,用上js所有关键字
  8. Java Web ConnectionPool (连接池技术)
  9. php 二维数组 根据值 找,PHP编程根据二维数组某个字段的值查找值所在的一维数组...
  10. 盒子模型代码_果冻公开课第五课:五分钟理清盒模型的前世今生