blob: c1027aedc794a4626e69691a254e30371a6ebe3f (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
|
package com.camilstaps.common;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
/**
* DatedString: a Date - String pair
* @author Camil Staps
*/
public class DatedString {
protected final Date date;
protected final String string;
public DatedString(Date date, String string) {
this.date = date;
this.string = string;
}
public String getString() {
return string;
}
public Date getDate() {
return date;
}
/**
* JSON-encode the pair so that it can be stored in SharedPreferences, for example
* @return
*/
@Override
public String toString() {
JSONObject json = new JSONObject();
try {
json.put("date", date.toString());
json.put("text", string);
} catch (JSONException e) {}
return json.toString();
}
/**
* JSON-decode some encoded pair
* @param s the String to decode
* @param castTo the specific class to cast to (may be DatedString or one of its children)
* @return
* @throws JSONException if the String was no valid JSON
* @throws ParseException if the date in the JSON was no valid Date
*/
public static Object fromString(String s, Class castTo) throws JSONException, ParseException {
JSONObject json = new JSONObject(s);
try {
return castTo.cast(castTo.getDeclaredConstructor(Date.class, String.class).newInstance(new Date(json.getString("date")), json.getString("text")));
} catch (InstantiationException e) {
return null;
} catch (IllegalAccessException e) {
return null;
} catch (InvocationTargetException e) {
return null;
} catch (NoSuchMethodException e) {
return null;
}
}
}
|