16
It is JSON feed from .Net service. I'm using this code:
它是。net服務的JSON提要。我用這段代碼:
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, JsonSerializer {
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() + ")/");
}
}
}
It registers custom serializer and deserializer for Date type. Using is simple: Gson gson = GsonHelper.createWcfGson(); and do what you want.
它為日期類型注冊自定義序列化器和反序列化器。使用方法很簡單:Gson Gson = GsonHelper.createWcfGson();做你想做的。
Upd: Sorry, previous example doesn't work with timezones. It's easier to use Calendar to take into account timezone offset. Code will look like this:
Upd:不好意思,前面的例子不適用於時區。使用日歷考慮時區偏移更容易。代碼如下所示:
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, JsonSerializer {
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() + ")/");
}
}
}
Then you can use returned Calendar object to get hours and minutes (and adjust timezone if needed).
然后可以使用返回的Calendar對象獲取小時和分鍾(如果需要,還可以調整時區)。
calendar.get(Calendar.HOUR_OF_DAY);
calendar.get(Calendar.MINUTE);