Это фид JSON из сервиса .Net. Я использую этот код:
public class GsonHelper {
public static Gson createWcfGson() {
GsonBuilder gsonb = new GsonBuilder();
gsonb.registerTypeAdapter(Date.class, new WcfDateDeserializer());
Gson gson = gsonb.create();
return gson;
}
private static class WcfDateDeserializer implements JsonDeserializer<Date>, JsonSerializer<Date> {
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
String JSONDateToMilliseconds = "\\/(Date\\((.*?)(\\+.*)?\\))\\/";
Pattern pattern = Pattern.compile(JSONDateToMilliseconds);
Matcher matcher = pattern.matcher(json.getAsJsonPrimitive().getAsString());
String result = matcher.replaceAll("$2");
return new Date(new Long(result));
}
@Override
public JsonElement serialize(Date date, Type arg1, JsonSerializationContext arg2) {
return new JsonPrimitive("/Date(" + date.getTime() + ")/");
}
}
}
Регистрирует пользовательский сериализатор и десериализатор для типа Date
. Использовать просто: Gson gson = GsonHelper.createWcfGson();
и делай что хочешь.
Upd: Извините, предыдущий пример не работает с часовыми поясами. Проще использовать Calendar
, чтобы учесть смещение часового пояса. Код будет выглядеть так:
public class GsonHelper {
public static Gson createWcfGson() {
GsonBuilder gsonb = new GsonBuilder();
gsonb.registerTypeAdapter(Date.class, new WcfCalendarDeserializer ());
Gson gson = gsonb.create();
return gson;
}
public static class WcfCalendarDeserializer implements JsonDeserializer<Calendar>, JsonSerializer<Calendar> {
public Calendar deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
String JSONDateToMilliseconds = "\\/(Date\\((.*?)(\\+.*)?\\))\\/";
Pattern pattern = Pattern.compile(JSONDateToMilliseconds);
Matcher matcher = pattern.matcher(json.getAsJsonPrimitive().getAsString());
matcher.matches();
String tzone = matcher.group(3);
String result = matcher.replaceAll("$2");
Calendar calendar = new GregorianCalendar();
calendar.setTimeZone(TimeZone.getTimeZone("GMT" + tzone));
calendar.setTimeInMillis(new Long(result));
return calendar;
}
@Override
public JsonElement serialize(Calendar calendar, Type arg1, JsonSerializationContext arg2) {
return new JsonPrimitive("/Date(" + calendar.getTimeInMillis() + ")/");
}
}
}
Затем вы можете использовать возвращенный Calendar
объект, чтобы получить часы и минуты (и при необходимости скорректировать часовой пояс).
calendar.get(Calendar.HOUR_OF_DAY);
calendar.get(Calendar.MINUTE);