利用gson解析和生成json数据(二)
来源:互联网 发布:中国进出口月度数据 编辑:程序博客网 时间:2024/06/05 08:40
包含枚举类型的对象转换成json字符串,首先需要定义一个实现JsonSerializer<T>,JsonDeserializer<T>接口的类
其中T代表我们自己定义的枚举类型
public class MySerializer implements JsonSerializer<ColorEnum>,JsonDeserializer<ColorEnum> {@Overridepublic ColorEnum deserialize(JsonElement json, Type arg1,JsonDeserializationContext arg2) throws JsonParseException {// TODO Auto-generated method stubif (json.getAsInt() < ColorEnum.values().length) {return ColorEnum.values()[json.getAsInt()];}return null;}@Overridepublic JsonElement serialize(ColorEnum colorEnum, Type arg1,JsonSerializationContext arg2) {// TODO Auto-generated method stubreturn new JsonPrimitive(colorEnum.ordinal());}}然后和普通的对象转换成json一样,如下:
JSONEnumEntity entity = new JSONEnumEntity("haha",ColorEnum.BLUE);Gson gson7 = new Gson();String jsonStr = gson7.toJson(entity);System.out.println(jsonStr);
Gson builder = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().serializeNulls().setDateFormat("yyyy-MM-dd HH:mm:ss").setPrettyPrinting()//格式化输出.setVersion(0).create();StudentEntity entity = new StudentEntity(1,"张三",new Date(1992-1900,2,22));//年份需要减去1900,月份从0开始计算String jsonStr = builder.toJson(entity);System.out.println(jsonStr);//-----------------------------------------------------------------------------System.out.println("---------------------------------------------------------");List<StudentEntity>entityList = new ArrayList<StudentEntity>();StudentEntity entity2 = new StudentEntity(2,"李四",new Date(1993-1900,5,20,20,31,52));entityList.add(entity);entityList.add(entity2);Type entityListType = new TypeToken<List<StudentEntity>>() {}.getType();jsonStr = builder.toJson(entityList, entityListType);System.out.println(jsonStr);
0 0
- 利用gson解析和生成json数据(二)
- 利用gson解析和生成json数据(一)
- GSON方式生成和解析json数据
- GSON方式生成和解析json数据
- google-GSON解析和生成JSON数据
- GSON方式生成和解析json数据
- GSON方式生成和解析json数据
- GSON方式生成和解析json数据
- GSON方式生成和解析json数据
- 使用Gson生成和解析json数据
- GSON方式生成和解析json数据
- 利用GSON解析JSON数据
- Android 利用Gson生成或解析json
- Android 利用Gson生成或解析json
- Volley学习(二)简封Volley、为Volley请求头体添加Json参数、Gson和JsonObject生成Json数据、Gson解析返回的Json
- android 利用Gson生成json数据
- 利用Gson快捷解析Json数据
- Android利用Gson解析Json数据
- HDU—— 2203 亲和串
- Android EditText限制文字长度(中文算2字符,英文算1字符)
- var关键字
- 牛腩 之HTML创建使用网页的文本对齐与格式化
- 【Allwinner ClassA20类库分析】4.GPIO类的使用
- 利用gson解析和生成json数据(二)
- Hibernate 注解中CascadeType用法汇总
- U盘在VMware下启动,虚拟机里优盘的启动方法
- 在网易云课堂开讲MOOC课《面向对象软件开发实践》
- OpenCV入门(二十六)-- 轮廓检测
- 简单制作 OS X Yosemite 10.10 正式版U盘USB启动安装盘方法教程 (全新安装 Mac 系统)
- 定义一个泛型静态方法,用于输出两个指定集合Collection集合的并、交和差集并验证
- 第十二周项目1-阅读程序(一)
- uvm cmd传递参数 $test$plusargs $value$plusargs