利用gson解析和生成json数据(二)

 包含枚举类型的对象转换成json字符串,首先需要定义一个实现JsonSerializer<T>,JsonDeserializer<T>接口的类

其中T代表我们自己定义的枚举类型

public class MySerializer implements JsonSerializer<ColorEnum>,JsonDeserializer<ColorEnum> {

		@Override
		public ColorEnum deserialize(JsonElement json, Type arg1,
				JsonDeserializationContext arg2) throws JsonParseException {
			// TODO Auto-generated method stub
			if (json.getAsInt() < ColorEnum.values().length) {
				return ColorEnum.values()[json.getAsInt()];
			}
			return null;
		}

		@Override
		public JsonElement serialize(ColorEnum colorEnum, Type arg1,
				JsonSerializationContext arg2) {
			// TODO Auto-generated method stub
			return 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);



你可能感兴趣的:(json,android,数据,格式化)