android 解析json 日期格式,使用Android上的GSON解析JSON日期格式為字符串

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);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值