Пожалуйста, попробуйте следующий код:
public class Main {
static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm'Z'";
static final Calendar calendar = Calendar.getInstance();
static class LongUtil {
static boolean isLong(String longValue) {
try {
Long.parseLong(longValue);
return true;
} catch (RuntimeException e) {
return false;
}
}
}
static class DateDeserializer implements JsonDeserializer<Date> {
final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_FORMAT);
@Override
public Date deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
System.out.println(type.getTypeName());
System.out.println(jsonElement.getAsJsonPrimitive());
if (jsonElement.getAsJsonPrimitive() != null) {
final String expectedDateValue = jsonElement.getAsJsonPrimitive().getAsString();
if (LongUtil.isLong(expectedDateValue)) {
System.out.println("It is long value hence parsing it to long");
calendar.setTimeInMillis(Long.parseLong(expectedDateValue));
return calendar.getTime();
} else {
System.out.println("It is dateformat value hence parsing it to dateformat");
try {
return simpleDateFormat.parse(expectedDateValue);
} catch (ParseException e) {
throw new JsonParseException("Invalud dateFormat while parsing");
}
}
} else {
throw new JsonParseException("JSOn Premitive Exception null");
}
}
}
public static void main(String[] args) throws IOException {
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Date.class, new DateDeserializer());
Gson gson = builder.create();
Type userListType = new TypeToken<ArrayList<Wrapper>>() {
}.getType();
File file = new File("response.json");
System.out.println("file exists : " + file.exists());
JsonReader jsonReader = new JsonReader(new FileReader(file));
List<Wrapper> wrapper = gson.fromJson(jsonReader, userListType);
System.out.println(wrapper);
}
class Wrapper {
User instance;
@Override
public String toString() {
return "Wrapper{" +
"instance=" + instance +
'}';
}
}
class User {
Location location;
Date timeAtLocation;
@Override
public String toString() {
return "User{" +
"location=" + location +
", timeAtLocation='" + timeAtLocation + '\'' +
'}';
}
}
class Location {
String lat;
String lon;
Date timestamp;
@Override
public String toString() {
return "Location{" +
"lat='" + lat + '\'' +
", lon='" + lon + '\'' +
", timestamp='" + timestamp + '\'' +
'}';
}
}
}
Объяснение:
В то время как deserializing
я проверяю, находится ли входная строка в dateformat
или в long
и основана на что я создаю экземпляр календаря, затем устанавливаю long и, наконец, получаю дату объекта даты, в противном случае просто используйте строку и отформатируйте ее на основе форматера даты.
Вывод:
file exists : true
It is long value hence parsing it to long
It is dateformat value hence parsing it to dateformat
It is long value hence parsing it to long
It is dateformat value hence parsing it to dateformat
[Wrapper{instance=User{location=Location{lat='31.522291', lon='-96.532816', timestamp='Fri May 01 13:49:08 IST 2020'}, timeAtLocation='Thu Apr 23 04:59:00 IST 2020'}}, Wrapper{instance=User{location=Location{lat='31.522291', lon='-96.532816', timestamp='Fri Jan 24 10:12:00 IST 2025'}, timeAtLocation='Mon Dec 23 04:59:00 IST 2019'}}]