public class CustomTypeAdapterFactory implements TypeAdapterFactory { public final TypeAdapter create(Gson gson, TypeToken type) { return new TypeAdapter() { @Override public void write(JsonWriter out, Object value) throws IOException { JsonElement tree = delegate.toJsonTree(value); //add code for writing object } @Override public Object read(JsonReader in) throws IOException { JsonElement tree = elementAdapter.read(in); //Add code for reading object } }; } }
/** * @return value to store. * @throws Exception * if value could not be retrieved */ protected Object getValue() throws Exception { return adapter.get(); // ...might be validly null } }
public static TypeAdapter on(Fixture target, Class<?> type) { TypeAdapter a = adapterFor(type); a.init(target, type); return a; }
private Object adaptArgumentToType(Class<?> parameterType, String argument) throws Exception { Object arg; try { arg = TypeAdapter.on(actor, parameterType).parse(argument); } catch (NumberFormatException e) { throw new CouldNotParseFitFailureException(argument, parameterType.getName()); } return arg; }
public static TypeAdapter on(Fixture fixture, Method method) { return on(fixture, method, false); }
@Override public Object parse(String s) throws Exception { StringTokenizer t = new StringTokenizer(s, ","); Object array = Array.newInstance(componentType, t.countTokens()); for (int i = 0; t.hasMoreTokens(); i++) { Array.set(array, i, componentAdapter.parse(t.nextToken().trim())); } return array; }
@Override public void init(Fixture target, Class<?> type) { super.init(target, type); componentType = type.getComponentType(); componentAdapter = on(target, componentType); }
public Object get() throws IllegalAccessException, InvocationTargetException { if (field != null) { return field.get(target); } if (method != null) { return invoke(); } return null; }
public boolean equals(Object a, Object b) { int length = Array.getLength(a); if (length != Array.getLength(b)) return false; for (int i = 0; i < length; i++) { if (!componentAdapter.equals(Array.get(a, i), Array.get(b, i))) return false; } return true; } }
public String toString(Object o) { if (o == null) return ""; int length = Array.getLength(o); StringBuffer b = new StringBuffer(5 * length); for (int i = 0; i < length; i++) { b.append(componentAdapter.toString(Array.get(o, i))); if (i < (length - 1)) { b.append(", "); } } return b.toString(); }
public static TypeAdapter on(Fixture fixture, Method method) { return on(fixture, method, false); }
private Object adaptArgumentToType(Class<?> parameterType, String argument) throws Exception { Object arg; try { arg = TypeAdapter.on(actor, parameterType).parse(argument); } catch (NumberFormatException e) { throw new CouldNotParseFitFailureException(argument, parameterType.getName()); } return arg; }