利用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);



将对象中的部分属性转换成字符串,需要在要转换的字段上加上@export注解

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
原创粉丝点击