List of usage examples for com.google.gson TypeAdapter TypeAdapter
TypeAdapter
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; }//from ww w . jav a 2 s. c om 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; }//w w w. j a va 2s . c om 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.carbondata.sdk.file.Schema.java
License:Apache License
/** * Create a Schema using JSON string, for example: * [//from ww w .j a v a 2 s . co m * {"name":"string"}, * {"age":"int"} * ] * @param json specified as string * @return Schema */ public static Schema parseJson(String json) { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(Field.class, new TypeAdapter<Field>() { @Override public void write(JsonWriter out, Field field) throws IOException { // noop } @Override public Field read(JsonReader in) throws IOException { in.beginObject(); Field field = new Field(in.nextName(), in.nextString()); in.endObject(); return field; } }); Field[] fields = gsonBuilder.create().fromJson(json, Field[].class); return new Schema(fields); }
From source file:org.apache.hadoop.fs.http.client.ContentSummary.java
License:Apache License
public static TypeAdapter adapter() { return new TypeAdapter<ContentSummary>() { @Override//from ww w.j a v a 2 s .c o m public void write(JsonWriter out, ContentSummary value) throws IOException { /* not implemented */ } @Override public ContentSummary read(JsonReader in) throws IOException { ContentSummary instance = null; in.setLenient(true); if (in.peek() == JsonToken.BEGIN_OBJECT) { in.beginObject(); if (in.nextName().equalsIgnoreCase("ContentSummary")) { String name; in.beginObject(); instance = new ContentSummary(); while (in.hasNext()) { name = in.nextName(); if (name.equalsIgnoreCase("directoryCount")) { instance.directoryCount = in.nextInt(); } else if (name.equalsIgnoreCase("fileCount")) { instance.fileCount = in.nextInt(); } else if (name.equalsIgnoreCase("length")) { instance.length = in.nextInt(); } else if (name.equalsIgnoreCase("quota")) { instance.quota = in.nextInt(); } else if (name.equalsIgnoreCase("spaceConsumed")) { instance.spaceConsumed = in.nextInt(); } else if (name.equalsIgnoreCase("spaceQuota")) { instance.spaceQuota = in.nextInt(); } } in.endObject(); } in.endObject(); } return instance; } }; }
From source file:org.apache.hadoop.fs.http.client.FileStatus.java
License:Apache License
public static TypeAdapter adapter() { return new TypeAdapter<FileStatus>() { @Override/*from ww w . jav a 2 s. c o m*/ public void write(JsonWriter out, FileStatus value) throws IOException { /* not implemented */ } @Override public FileStatus read(JsonReader in) throws IOException { FileStatus instance = null; in.setLenient(true); if (in.peek() == JsonToken.BEGIN_OBJECT) { in.beginObject(); if (in.nextName().equalsIgnoreCase("FileStatus")) { String name; in.beginObject(); instance = new FileStatus(); while (in.hasNext()) { name = in.nextName(); if (name.equalsIgnoreCase("accessTime")) { instance.accessTime = in.nextLong(); } else if (name.equalsIgnoreCase("blockSize")) { instance.blockSize = in.nextInt(); } else if (name.equalsIgnoreCase("length")) { instance.length = in.nextLong(); } else if (name.equalsIgnoreCase("modificationTime")) { instance.modTime = in.nextLong(); } else if (name.equalsIgnoreCase("replication")) { instance.replication = in.nextInt(); } else if (name.equalsIgnoreCase("group")) { instance.group = in.nextString(); } else if (name.equalsIgnoreCase("owner")) { instance.owner = in.nextString(); } else if (name.equalsIgnoreCase("pathSuffix")) { instance.suffix = in.nextString(); } else if (name.equalsIgnoreCase("permission")) { instance.permission = in.nextString(); } else if (name.equalsIgnoreCase("type")) { instance.type = FileType.valueOf(in.nextString()); } } in.endObject(); } in.endObject(); } return instance; } }; }
From source file:org.apache.samza.table.utils.SerdeUtils.java
License:Apache License
/** * Helper method to serialize Java objects as json strings * @param name name of object used for logging * @param object object to be serialized * @return Json representation of the object *//*from w w w . jav a 2 s. c om*/ public static String toJson(String name, Object object) { final Gson gson = new GsonBuilder().excludeFieldsWithModifiers(Modifier.TRANSIENT, Modifier.STATIC) // Tells Gson how to serialize fields with type of Class. .registerTypeHierarchyAdapter(Class.class, new TypeAdapter<Class>() { @Override public void write(JsonWriter out, Class value) throws IOException { if (value == null) { out.nullValue(); } else { out.value(value.getName()); } } @Override public Class read(JsonReader in) { throw new SamzaException("Deserialization from json is not supported."); } }).create(); try { return gson.toJson(object); } catch (Exception e) { throw new SamzaException(String.format("Failed to serialize %s to json", name), e); } }
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; }// w w w. ja v a 2 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); 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/*from ww w. j av a2 s . c om*/ 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 w ww .ja v a 2s .c o m*/ 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 ww. ja v a2 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; } }; }