Gson序列化与反序列化
Data obj= new Gson().fromJson(dataStr, Data.class);
String dataStr = new Gson().toJson(obj)
Gson日期格式化
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
Gson注册序列化适配器
Gson gson = new GsonBuilder().registerTypeAdapter(LocalDateTime.class, new JsonSerializer<LocalDateTime>() {
@Override
public JsonElement serialize(LocalDateTime src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(src.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
}}).registerTypeAdapter(LocalDate.class, new JsonSerializer<LocalDate>() {
@Override
public JsonElement serialize(LocalDate src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(src.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
}).create();
Gson注册反序列化适配器
Gson gson = new GsonBuilder().registerTypeAdapter(LocalDateTime.class, new JsonDeserializer<LocalDateTime>() {
@Override
public LocalDateTime deserialize(JsonElement json, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
String datetime = json.getAsJsonPrimitive().getAsString();
return LocalDateTime.parse(datetime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
}}).registerTypeAdapter(LocalDate.class, new JsonDeserializer<LocalDate>() {
@Override
public LocalDate deserialize(JsonElement json, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
String datetime = json.getAsJsonPrimitive().getAsString();
return LocalDate.parse(datetime, DateTimeFormatter.ofPattern("yyyy-MM-dd"));}}).create();
|