From fd3e6497802e7fc549c7c03077abe9ebb957109d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Konstantin=20Simon=20Maria=20M=C3=B6llers?= Date: Fri, 23 Jan 2015 02:40:31 +0100 Subject: [PATCH] Added date functionality. --- JSONObject.java | 19 +++++++++++++++++++ JSONTokener.java | 31 ++++++++++++++++++++++++++++++- 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/JSONObject.java b/JSONObject.java index d66623110..a69590013 100755 --- a/JSONObject.java +++ b/JSONObject.java @@ -31,6 +31,7 @@ of this software and associated documentation files (the "Software"), to deal import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Collection; +import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; @@ -581,6 +582,24 @@ public JSONObject getJSONObject(String key) throws JSONException { + "] is not a JSONObject."); } + /** + * Get the Date value associated with a key. + * + * @param key + * A key string. + * @return A JSONObject which is the value. + * @throws JSONException + * if the key is not found or if the value is not a JSONObject. + */ + public Date getDate(String key) throws JSONException { + Object object = this.get(key); + if (object instanceof Date) { + return (Date) object; + } + throw new JSONException("JSONObject[" + quote(key) + + "] is not a Date."); + } + /** * Get the long value associated with a key. * diff --git a/JSONTokener.java b/JSONTokener.java index 32548ed9f..4dd3b9b7d 100644 --- a/JSONTokener.java +++ b/JSONTokener.java @@ -6,6 +6,7 @@ import java.io.InputStreamReader; import java.io.Reader; import java.io.StringReader; +import java.util.GregorianCalendar; /* Copyright (c) 2002 JSON.org @@ -358,7 +359,7 @@ public Object nextValue() throws JSONException { switch (c) { case '"': case '\'': - return this.nextString(c); + return this.checkDates(this.nextString(c)); case '{': this.back(); return new JSONObject(this); @@ -390,6 +391,34 @@ public Object nextValue() throws JSONException { return JSONObject.stringToValue(string); } + /** + * Checks a string for dates. + * + * @param s string to check + * @return passed through string or a Date object + */ + private Object checkDates(String s) { + if (s.length() == 10 || s.length() == 20) { + if (s.charAt(4) == '-' && s.charAt(7) == '-') { + int year = Integer.valueOf(s.substring(0, 4)); + int month = Integer.valueOf(s.substring(5, 7)); + int day = Integer.valueOf(s.substring(8, 10)); + + if (s.length() == 20 && s.charAt(10) == 'T' && s.charAt(13) == ':' && s.charAt(16) == ':' && s.charAt(19) == 'Z') { + int hour = Integer.valueOf(s.substring(11, 13)); + int mins = Integer.valueOf(s.substring(14, 16)); + int secs = Integer.valueOf(s.substring(17, 19)); + + return new GregorianCalendar(year, month, day, hour, mins, secs).getTime(); + } + + return new GregorianCalendar(year, month, day).getTime(); + } + } + + return s; + } + /** * Skip characters until the next character is the requested character.