Google Gson解析Json数据应用实例

来源:互联网 发布:数据挖掘聚类 编辑:程序博客网 时间:2024/05/20 22:26

 /**

     * 带日期类型Bean、Json相互转换

     */

    @Test

    public void testDateBeanJson() {

       // 日期Bean数据

       DateBean bean = new DateBean("1001", "scott", 20, new Date());

       

       // Bean(带日期属性) -> Json

       gson = gsonBuilder.registerTypeAdapter(java.util.Date.class

              new DateSerializerUtils()).setDateFormat(DateFormat.LONG).create();

       String json = gson.toJson(bean);

       System.out.println(json);

       

       // Json -> Bean(带日期类型属性)

       gson = gsonBuilder.registerTypeAdapter(java.util.Date.class

              new DateDeserializerUtils()).setDateFormat(DateFormat.LONG).create();

       java.lang.reflect.Type type = 

           new com.google.gson.reflect.TypeToken<DateBean>(){}.getType();

       DateBean b = gson.fromJson(json, type);

       System.out.println(b);

    }

 

    /**

     * 泛型日期List、Json相互转换

     */

    @Test

    public void testDateGenericListJson() {

       // 泛型日期List

       List<DateBean> list = new ArrayList<DateBean>();

       for(int i = 0; i < 3; i++) {

           DateBean user = new DateBean("100" + i, "name" + i, 20 + i, new Date());

           list.add(user);

       }

       System.out.println(list);

       

       // 泛型日期List -> Json

       gson = gsonBuilder.registerTypeAdapter(java.util.Date.class

              new DateSerializerUtils()).setDateFormat(DateFormat.LONG).create();

       java.lang.reflect.Type type = 

           new com.google.gson.reflect.TypeToken<List<DateBean>>(){}.getType();

       String json = gson.toJson(list, type);

       System.out.println(json);   

       

       // Json -> 泛型日期List

       gson = gsonBuilder.registerTypeAdapter(java.util.Date.class

              new DateDeserializerUtils()).setDateFormat(DateFormat.LONG).create();

       List<DateBean> users = gson.fromJson(json.toString(), type);

       System.out.println(users);

    }

}