VVL1295

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Gson序列化--序列化Key为自定义类的Map

  原来很简单:

public class CasualTest {
    public static void main(String[] args) {
        Map<Point, List<Point>> map = new LinkedHashMap<Point, List<Point>>();
        
        Point order = new Point(1,2);
        
        Point item = new Point(1,2);
        List<Point> itemList = new ArrayList<Point>();
        itemList.add(item);
        
        map.put(order, itemList);
        Gson gson = new GsonBuilder().enableComplexMapKeySerialization()
                .create();
        String string = gson.toJson(map);
        System.out.println(string);
        Map<Point, List<Point>> map2 = gson.fromJson(string, new TypeToken<Map<Point, List<Point>>>(){}.getType());
        System.out.println(map2);
        
    }
}

  

  输出打印为:

  [[{"x":1,"y":2},[{"x":1,"y":2}]]]
  {{x=1.0, y=2.0}=[{x=1.0, y=2.0}]}

  打印出来的第一行表明gson会把自定义类作为key类型的map序列化成数组嵌套数组,然后被嵌套的数组的第一个元素是一个对象,该对象由自定义类对象序列化而成,第二个元素是一个数组,那么这个被嵌套的数组就对应着一个entry,最外层的数组就对应着map;打印出来的第二行,表明反序列化没问题。

  

  那么如果没有这样实例化gson,采用最简单的方式实例化gson(Gson gson = new Gsin();),程序就会抛出类似这样的异常:

com.google.gson.JsonParseException: Expecting object found: "com.gpl.po.TradeOrderPO@56760663"

  这异常的意思是,gson打算找到一个对象,但是得到的是"com.gpl.po.TradeOrderPO@56760663",这是调用这个类的toString()方法得到的字符串,因为采用那种简单方式实例化得到的gson对象无法序列化作为map的key的自定义类对象,所以只得到代用该类toString()方法得到的字符串。

 

posted on 2016-01-15 10:03  bobo2018  阅读(565)  评论(0)    收藏  举报