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