List of usage examples for com.google.gson.reflect TypeToken getRawType
public final Class<? super T> getRawType()
From source file:net.friendscraft_2_launch.launcher.json.EnumAdaptorFactory.java
License:Apache License
@SuppressWarnings("unchecked") @Override//from w ww . j av a2s. co m public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { if (!type.getRawType().isEnum()) return null; final Map<String, T> map = new HashMap<String, T>(); for (T c : (T[]) type.getRawType().getEnumConstants()) { map.put(c.toString().toLowerCase(Locale.US), c); } return new TypeAdapter<T>() { @Override public T read(JsonReader reader) throws IOException { if (reader.peek() == JsonToken.NULL) { reader.nextNull(); return null; } String name = reader.nextString(); if (name == null) return null; return map.get(name.toLowerCase(Locale.US)); } @Override public void write(JsonWriter writer, T value) throws IOException { if (value == null) { writer.nullValue(); } else { writer.value(value.toString().toLowerCase(Locale.US)); } } }; }
From source file:net.minecrell.workbench.tools.util.gson.LowerCaseEnumTypeAdapterFactory.java
License:Open Source License
@Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { @SuppressWarnings("unchecked") Class<T> rawType = (Class<T>) type.getRawType(); if (!rawType.isEnum()) { return null; }/* ww w . java2 s .com*/ final Map<String, T> lookup = new HashMap<>(); for (T constant : rawType.getEnumConstants()) { lookup.put(toLowerCase(constant), constant); } return new TypeAdapter<T>() { @Override public void write(JsonWriter out, T value) throws IOException { if (value == null) { out.nullValue(); } else { out.value(toLowerCase(value)); } } @Override public T read(JsonReader reader) throws IOException { if (reader.peek() == JsonToken.NULL) { reader.nextNull(); return null; } else { return lookup.get(reader.nextString()); } } }; }
From source file:net.oneandone.stool.configuration.adapter.ExtensionsAdapter.java
License:Apache License
public static TypeAdapterFactory factory(final ExtensionsFactory factory) { return new TypeAdapterFactory() { @SuppressWarnings("unchecked") public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { if (type.getRawType().equals(Extensions.class)) { return (TypeAdapter<T>) new ExtensionsAdapter(gson, factory); }/*from w ww .j av a 2s .co m*/ return null; } }; }
From source file:net.technicpack.launchercore.util.LowerCaseEnumTypeAdapterFactory.java
License:Open Source License
@SuppressWarnings("unchecked") public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { Class rawType = type.getRawType(); if (!rawType.isEnum()) { return null; }/*w w w .j a v a 2s.co m*/ final Map<String, T> lowercaseToConstant = new HashMap<String, T>(); for (Object constant : rawType.getEnumConstants()) { lowercaseToConstant.put(toLowercase(constant), (T) constant); } return new TypeAdapter<T>() { public void write(JsonWriter out, T value) throws IOException { if (value == null) out.nullValue(); else out.value(LowerCaseEnumTypeAdapterFactory.this.toLowercase(value)); } public T read(JsonReader reader) throws IOException { if (reader.peek() == JsonToken.NULL) { reader.nextNull(); return null; } return lowercaseToConstant.get(reader.nextString()); } }; }
From source file:networkUtils.RuntimeTypeAdapterFactory.java
License:Apache License
public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) { if (type.getRawType() != baseType) { return null; }/*from ww w. ja va2 s.c o m*/ final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<String, TypeAdapter<?>>(); final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<Class<?>, TypeAdapter<?>>(); for (Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) { TypeAdapter<?> delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue())); labelToDelegate.put(entry.getKey(), delegate); subtypeToDelegate.put(entry.getValue(), delegate); } return new TypeAdapter<R>() { @Override public R read(JsonReader in) throws IOException { JsonElement jsonElement = Streams.parse(in); String label = predicate.process(jsonElement); @SuppressWarnings("unchecked") // registration requires that subtype extends T TypeAdapter<R> delegate = (TypeAdapter<R>) labelToDelegate.get(label); if (delegate == null) { throw new JsonParseException("cannot deserialize " + baseType + " subtype named " + label + "; did you forget to register a subtype?"); } return delegate.fromJsonTree(jsonElement); } @Override public void write(JsonWriter out, R value) throws IOException { // Unimplemented as we don't use write. /*Class<?> srcType = value.getClass(); String label = subtypeToLabel.get(srcType); @SuppressWarnings("unchecked") // registration requires that subtype extends T TypeAdapter<R> delegate = (TypeAdapter<R>) subtypeToDelegate.get(srcType); if (delegate == null) { throw new JsonParseException("cannot serialize " + srcType.getName() + "; did you forget to register a subtype?"); } JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject(); if (jsonObject.has(typeFieldName)) { throw new JsonParseException("cannot serialize " + srcType.getName() + " because it already defines a field named " + typeFieldName); } JsonObject clone = new JsonObject(); clone.add(typeFieldName, new JsonPrimitive(label)); for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) { clone.add(e.getKey(), e.getValue()); }*/ Streams.write(null, out); } }; }
From source file:org.apache.zeppelin.display.RuntimeTypeAdapterFactory.java
License:Apache License
public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) { if (type.getRawType() != baseType) { return null; }//from w ww . j a v a 2s . com final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<String, TypeAdapter<?>>(); final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<Class<?>, TypeAdapter<?>>(); for (Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) { TypeAdapter<?> delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue())); labelToDelegate.put(entry.getKey(), delegate); subtypeToDelegate.put(entry.getValue(), delegate); } return new TypeAdapter<R>() { @Override public R read(JsonReader in) throws IOException { JsonElement jsonElement = Streams.parse(in); JsonElement labelJsonElement = jsonElement.getAsJsonObject().remove(typeFieldName); String label = (labelJsonElement == null ? null : labelJsonElement.getAsString()); @SuppressWarnings("unchecked") // registration requires that subtype extends T TypeAdapter<R> delegate = (TypeAdapter<R>) labelToDelegate.get(label); if (delegate == null) { throw new JsonParseException("cannot deserialize " + baseType + " subtype named " + label + "; did you forget to register a subtype?"); } return delegate.fromJsonTree(jsonElement); } @Override public void write(JsonWriter out, R value) throws IOException { Class<?> srcType = value.getClass(); String label = subtypeToLabel.get(srcType); @SuppressWarnings("unchecked") // registration requires that subtype extends T TypeAdapter<R> delegate = (TypeAdapter<R>) subtypeToDelegate.get(srcType); if (delegate == null) { throw new JsonParseException( "cannot serialize " + srcType.getName() + "; did you forget to register a subtype?"); } JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject(); if (jsonObject.has(typeFieldName) && !srcType.getSimpleName().equals("OldInput")) { throw new JsonParseException("cannot serialize " + srcType.getName() + " because it already defines a field named " + typeFieldName); } JsonObject clone = new JsonObject(); if (!srcType.getSimpleName().equals("OldInput")) { clone.add(typeFieldName, new JsonPrimitive(label)); } for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) { clone.add(e.getKey(), e.getValue()); } Streams.write(clone, out); } }.nullSafe(); }
From source file:org.arl.fjage.remote.ArrayAdapterFactory.java
License:BSD License
@SuppressWarnings("unchecked") public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { final Class<T> rawType = (Class<T>) type.getRawType(); if (!rawType.isArray()) return null; final Class<?> compType = rawType.getComponentType(); if (compType == null) return null; if (!compType.isPrimitive()) return null; if (!compType.equals(byte.class) && !compType.equals(int.class) && !compType.equals(short.class) && !compType.equals(long.class) && !compType.equals(float.class) && !compType.equals(double.class)) return null; final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type); return new TypeAdapter<T>() { @Override// w ww . j a va 2 s. c o m public void write(JsonWriter out, T value) throws IOException { if (value == null) out.nullValue(); else { byte[] data; if (compType.equals(byte.class)) data = (byte[]) value; else { ByteBuffer buf = null; if (compType.equals(int.class)) { buf = ByteBuffer.allocate(Integer.SIZE / Byte.SIZE * ((int[]) value).length) .order(ByteOrder.LITTLE_ENDIAN); buf.asIntBuffer().put((int[]) value); } else if (compType.equals(short.class)) { buf = ByteBuffer.allocate(Short.SIZE / Byte.SIZE * ((short[]) value).length) .order(ByteOrder.LITTLE_ENDIAN); buf.asShortBuffer().put((short[]) value); } else if (compType.equals(long.class)) { buf = ByteBuffer.allocate(Long.SIZE / Byte.SIZE * ((long[]) value).length) .order(ByteOrder.LITTLE_ENDIAN); buf.asLongBuffer().put((long[]) value); } else if (compType.equals(float.class)) { buf = ByteBuffer.allocate(Float.SIZE / Byte.SIZE * ((float[]) value).length) .order(ByteOrder.LITTLE_ENDIAN); buf.asFloatBuffer().put((float[]) value); } else if (compType.equals(double.class)) { buf = ByteBuffer.allocate(Double.SIZE / Byte.SIZE * ((double[]) value).length) .order(ByteOrder.LITTLE_ENDIAN); buf.asDoubleBuffer().put((double[]) value); } data = buf.array(); } if (bare) out.value(Base64.getEncoder().encodeToString(data)); else { out.beginObject(); out.name("clazz").value(rawType.getName()); out.name("data").value(Base64.getEncoder().encodeToString(data)); out.endObject(); } } } @Override public T read(JsonReader in) throws IOException { JsonToken tok = in.peek(); if (tok == JsonToken.NULL) { in.nextNull(); return null; } if (tok == JsonToken.STRING) return decodeString(in.nextString()); if (tok == JsonToken.BEGIN_ARRAY) return delegate.read(in); if (tok != JsonToken.BEGIN_OBJECT) return null; T rv = null; in.beginObject(); while (in.hasNext()) { String name = in.nextName(); if (name.equals("data")) rv = decodeString(in.nextString()); else in.skipValue(); } in.endObject(); return rv; } private T decodeString(String s) { byte[] data = Base64.getDecoder().decode(s); if (compType.equals(byte.class)) return (T) data; ByteBuffer buf = ByteBuffer.wrap(data); if (compType.equals(int.class)) { IntBuffer buf2 = ByteBuffer.wrap(Base64.getDecoder().decode(s)).order(ByteOrder.LITTLE_ENDIAN) .asIntBuffer(); int[] array = new int[buf2.limit()]; buf2.get(array); return (T) array; } if (compType.equals(short.class)) { ShortBuffer buf2 = ByteBuffer.wrap(Base64.getDecoder().decode(s)).order(ByteOrder.LITTLE_ENDIAN) .asShortBuffer(); short[] array = new short[buf2.limit()]; buf2.get(array); return (T) array; } if (compType.equals(long.class)) { LongBuffer buf2 = ByteBuffer.wrap(Base64.getDecoder().decode(s)).order(ByteOrder.LITTLE_ENDIAN) .asLongBuffer(); long[] array = new long[buf2.limit()]; buf2.get(array); return (T) array; } if (compType.equals(float.class)) { FloatBuffer buf2 = ByteBuffer.wrap(Base64.getDecoder().decode(s)).order(ByteOrder.LITTLE_ENDIAN) .asFloatBuffer(); float[] array = new float[buf2.limit()]; buf2.get(array); return (T) array; } if (compType.equals(double.class)) { DoubleBuffer buf2 = ByteBuffer.wrap(Base64.getDecoder().decode(s)) .order(ByteOrder.LITTLE_ENDIAN).asDoubleBuffer(); double[] array = new double[buf2.limit()]; buf2.get(array); return (T) array; } return null; } }; }
From source file:org.arl.fjage.remote.GenericValueAdapterFactory.java
License:BSD License
public <T> TypeAdapter<T> create(final Gson gson, TypeToken<T> type) { final Class<T> rawType = (Class<T>) type.getRawType(); if (!rawType.equals(GenericValue.class)) return null; final GenericValueAdapterFactory parent = this; return new TypeAdapter<T>() { @Override/*from www. j ava 2 s . com*/ public void write(JsonWriter out, T value) throws IOException { if (value == null) { out.nullValue(); return; } Class type = ((GenericValue) value).getType(); if (type == null) { out.nullValue(); return; } if (Number.class.isAssignableFrom(type)) out.value((Number) ((GenericValue) value).getValue()); else if (type.equals(String.class)) out.value((String) ((GenericValue) value).getValue()); else if (type.equals(Boolean.class)) out.value((Boolean) ((GenericValue) value).getValue()); else { out.beginObject(); out.name("clazz").value(type.getName()); out.name("data"); TypeAdapter delegate = gson.getAdapter(TypeToken.get(type)); Object v = ((GenericValue) value).getValue(); delegate.write(out, v); out.endObject(); } } @Override public T read(JsonReader in) throws IOException { JsonToken tok = in.peek(); if (tok == JsonToken.NULL) { in.nextNull(); return null; } if (tok == JsonToken.NUMBER) { String s = in.nextString(); try { if (s.contains(".")) return (T) new GenericValue(Double.parseDouble(s)); else return (T) new GenericValue(Long.parseLong(s)); } catch (NumberFormatException ex) { return (T) new GenericValue(null); } } if (tok == JsonToken.STRING) return (T) new GenericValue(in.nextString()); if (tok == JsonToken.BOOLEAN) return (T) new GenericValue(in.nextBoolean()); if (tok != JsonToken.BEGIN_OBJECT) return null; TypeToken tt = null; GenericValue rv = null; in.beginObject(); while (in.hasNext()) { String name = in.nextName(); if (name.equals("clazz")) { try { Class<?> cls = Class.forName(in.nextString()); tt = TypeToken.get(cls); } catch (Exception ex) { // do nothing } } else if (name.equals("data") && tt != null) { TypeAdapter delegate = gson.getAdapter(tt); rv = new GenericValue(delegate.read(in)); } else in.skipValue(); } in.endObject(); return (T) rv; } }; }
From source file:org.arl.fjage.remote.MessageAdapterFactory.java
License:BSD License
@SuppressWarnings("unchecked") public <T> TypeAdapter<T> create(final Gson gson, TypeToken<T> type) { final Class<T> rawType = (Class<T>) type.getRawType(); if (!Message.class.isAssignableFrom(rawType)) return null; final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type); final TypeAdapter<Performative> perfDelegate = gson.getAdapter(TypeToken.get(Performative.class)); final TypeAdapter<AgentID> aidDelegate = gson.getAdapter(TypeToken.get(AgentID.class)); final TypeAdapter<GenericValue> gvDelegate = gson.getAdapter(TypeToken.get(GenericValue.class)); final MessageAdapterFactory parent = this; return new TypeAdapter<T>() { @Override//from w w w. j av a 2 s . c om public void write(JsonWriter out, T value) throws IOException { if (value == null) out.nullValue(); else { out.beginObject(); out.name("clazz").value(value.getClass().getName()); out.name("data"); if (value instanceof GenericMessage) { GenericMessage msg = (GenericMessage) value; out.beginObject(); out.name("msgID").value(msg.getMessageID()); out.name("inReplyTo").value(msg.getInReplyTo()); out.name("perf"); perfDelegate.write(out, msg.getPerformative()); out.name("recipient"); aidDelegate.write(out, msg.getRecipient()); out.name("sender"); aidDelegate.write(out, msg.getSender()); out.name("map"); delegate.write(out, value); out.endObject(); } else delegate.write(out, value); out.endObject(); } } @Override public T read(JsonReader in) throws IOException { if (in.peek() == JsonToken.NULL) { in.nextNull(); return null; } T rv = null; Class<?> cls = null; in.beginObject(); while (in.hasNext()) { String name = in.nextName(); if (name.equals("clazz")) { String className = in.nextString(); try { cls = classloader != null ? Class.forName(className, true, classloader) : Class.forName(className); } catch (Exception ex) { // do nothing } } else if (name.equals("data")) { if (cls == null) rv = delegate.read(in); else if (cls.equals(GenericMessage.class)) { GenericMessage msg = new GenericMessage(); in.beginObject(); while (in.hasNext()) { String fname = in.nextName(); if (fname.equals("msgID")) msg.setMessageID(in.nextString()); else if (fname.equals("inReplyTo")) msg.setInReplyTo(in.nextString()); else if (fname.equals("perf")) msg.setPerformative(perfDelegate.read(in)); else if (fname.equals("recipient")) msg.setRecipient(aidDelegate.read(in)); else if (fname.equals("sender")) msg.setSender(aidDelegate.read(in)); else if (fname.equals("map")) { in.beginObject(); while (in.hasNext()) { String key = in.nextName(); GenericValue value = gvDelegate.read(in); msg.put(key, value); } in.endObject(); } else in.skipValue(); } in.endObject(); rv = (T) msg; } else { TypeAdapter<?> delegate1 = gson.getDelegateAdapter(parent, TypeToken.get(cls)); rv = (T) delegate1.read(in); } } else in.skipValue(); } in.endObject(); return rv; } }; }
From source file:org.brunocvcunha.digesteroids.cast.DigesteroidsDefaultCaster.java
License:Apache License
@SuppressWarnings("unchecked") @Override/*from w w w . j av a 2 s .c o m*/ public <T> T cast(Object value, Type targetType, String source) { if (value == null) { return null; } TypeToken<T> typeToken = (TypeToken<T>) TypeToken.get(targetType); Class<T> toClazz = (Class<T>) typeToken.getRawType(); log.debug("Handling value conversion (" + value.getClass() + " / " + value.toString() + ") to " + toClazz); if (toClazz.isAssignableFrom(String.class)) { return (T) string(value); } if (toClazz.isAssignableFrom(Byte.class)) { return (T) Byte.valueOf(value.toString()); } if (toClazz.isAssignableFrom(Short.class)) { return (T) Short.valueOf(value.toString()); } if (toClazz.isAssignableFrom(Integer.class)) { return (T) Integer.valueOf(Double.valueOf(value.toString()).intValue()); } if (toClazz.isAssignableFrom(Long.class)) { return (T) Long.valueOf(Double.valueOf(value.toString()).longValue()); } if (toClazz.isAssignableFrom(Double.class)) { return (T) Double.valueOf(value.toString()); } if (toClazz.isAssignableFrom(Date.class)) { return (T) date(value); } // throw new IllegalArgumentException("Need to convert value (" + value.getClass() + " / " + value.toString() + ") to " + toClazz); if (value instanceof String) { try { return gson.fromJson((String) value, targetType); } catch (Exception e) { //it's ok log.debug("Exception trying to convert string to type", e); } } return gson.fromJson(gson.toJson(value), targetType); }