List of usage examples for com.google.gson TypeAdapter read
public abstract T read(JsonReader in) throws IOException;
From source file:org.mule.runtime.extension.internal.persistence.ModelPropertyMapTypeAdapter.java
License:Open Source License
@Override public HierarchyClassMap<ModelProperty> read(JsonReader in) throws IOException { final HierarchyClassMap<ModelProperty> modelPropertyHashMap = new HierarchyClassMap<>(); in.beginObject();/* w w w .jav a 2 s. c o m*/ while (in.hasNext()) { final Class<? extends ModelProperty> type = getClassForModelProperty(in.nextName()); final TypeAdapter<?> adapter = gson.getAdapter(type); final ModelProperty read = (ModelProperty) adapter.read(in); modelPropertyHashMap.put(type, read); } in.endObject(); return modelPropertyHashMap; }
From source file:org.objectpocket.gson.CustomTypeAdapterFactory.java
License:Apache License
@Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type); // @Entity/*from w w w .j ava 2s . c o m*/ if (type.getRawType().getAnnotation(Entity.class) != null) { return new TypeAdapter<T>() { // SERIALIZE public void write(JsonWriter out, T obj) throws IOException { if (obj != null) { String id = objectPocket.getIdForObject(obj); // normalize if (!objectPocket.isSerializeAsRoot(obj)) { gson.toJson(new ProxyOut(obj.getClass().getTypeName(), id), ProxyOut.class, out); return; } else { objectPocket.setSerializeAsRoot(obj, false); } } // default serialization delegate.write(out, obj); }; // DESERIALIZE @SuppressWarnings("unchecked") @Override public T read(JsonReader in) throws IOException { if (in.getPath().length() > 2) { in.beginObject(); in.nextName(); StringBuilder sb = new StringBuilder(in.nextString()); String id = sb.substring(0, sb.indexOf("@")); in.endObject(); T obj = null; try { obj = (T) ReflectionUtil.instantiateDefaultConstructor(type.getRawType()); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException | NoSuchMethodException | InvocationTargetException e) { throw new IOException("Could not instantiate class " + type.getRawType().getName() + "\n" + "Might be that the class has no default constructor!", e); } objectPocket.addIdFromReadObject(obj, id); return obj; } else { T obj = delegate.read(in); return obj; } } }; } // All other else { return delegate; } }
From source file:org.openhab.binding.mqtt.homeassistant.internal.ChannelConfigurationTypeAdapterFactory.java
License:Open Source License
/** * Handle {@link BaseChannelConfiguration} * * @param gson/*from w ww . ja v a 2 s .c o m*/ * @param type * @return */ private <T> TypeAdapter<T> createHAConfig(Gson gson, TypeToken<T> type) { /* The delegate is the 'default' adapter */ final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type); return new TypeAdapter<T>() { @Override public T read(@Nullable JsonReader in) throws IOException { if (in == null) { return null; } /* read the object using the default adapter, but translate the names in the reader */ T result = delegate.read(MappingJsonReader.getConfigMapper(in)); /* do the '~' expansion afterwards */ expandTidleInTopics(BaseChannelConfiguration.class.cast(result)); return result; } @Override public void write(@Nullable JsonWriter out, T value) throws IOException { delegate.write(out, value); } }; }
From source file:org.openhab.binding.mqtt.homeassistant.internal.ChannelConfigurationTypeAdapterFactory.java
License:Open Source License
private <T> TypeAdapter<T> createHADevice(Gson gson, TypeToken<T> type) { /* The delegate is the 'default' adapter */ final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type); return new TypeAdapter<T>() { @Override/*from w w w. j ava2 s . c om*/ public T read(@Nullable JsonReader in) throws IOException { if (in == null) { return null; } /* read the object using the default adapter, but translate the names in the reader */ T result = delegate.read(MappingJsonReader.getDeviceMapper(in)); return result; } @Override public void write(@Nullable JsonWriter out, T value) throws IOException { delegate.write(out, value); } }; }
From source file:org.sprintapi.hyperdata.gson.HyperDataTypeAdapter.java
License:Apache License
@SuppressWarnings({ "unchecked", "rawtypes" }) @Override//from w w w .j a v a 2 s . co m public Object read(JsonReader in) throws IOException { if (in.peek() == JsonToken.NULL) { in.nextNull(); return null; } Object instance = constructor.construct(); BoundField metadataField = null; if (metadataAccess != null) { metadataField = boundFields.get(metadataAccess.fieldName); } Object meta = null; Map<String, BoundField> metaBoundFields = null; try { in.beginObject(); while (in.hasNext()) { String name = in.nextName(); if ((name != null) && (metadataField != null) && (name.startsWith(Constants.META_CHAR))) { if (meta == null) { meta = constructorConstructor.get(metadataField.type).construct(); if (!Map.class.isAssignableFrom(meta.getClass())) { metaBoundFields = reflectiveFactory.getBoundFields(gson, metadataField.type, metadataField.type.getRawType()); } } if (metaBoundFields != null) { BoundField field = metaBoundFields.get(name.substring(1)); if (field == null || !field.deserialized) { in.skipValue(); } else { field.read(in, meta); } } else { TypeAdapter<Object> ta = gson.getAdapter(Object.class); Object value = ta.read(in); ((Map) meta).put(name.substring(1), value); } } else if ((name != null) && (!name.equals(metadataAccess.fieldName))) { BoundField field = boundFields.get(name); if (field == null || !field.deserialized) { in.skipValue(); } else { field.read(in, instance); } } } if (metadataAccess.setter != null) { metadataAccess.setter.invoke(instance, meta); //TODO } } catch (IllegalStateException e) { throw new JsonSyntaxException(e); } catch (IllegalAccessException e) { throw new AssertionError(e); } catch (IllegalArgumentException e) { throw new AssertionError(e); } catch (InvocationTargetException e) { throw new AssertionError(e); } in.endObject(); return instance; }
From source file:org.terasology.rendering.nui.layers.mainMenu.ServerListDownloader.java
License:Apache License
private void download(String address) throws IOException { status = "Downloading server list .."; URL url = new URL("http", address, "/servers/list"); try (Reader reader = new InputStreamReader(url.openStream(), charset); JsonReader jsonReader = new JsonReader(reader)) { status = "Parsing content .."; jsonReader.beginArray();// w w w .j av a2 s . c om TypeAdapter<ServerInfo> adapter = GSON.getAdapter(ServerInfo.class); while (jsonReader.hasNext()) { ServerInfo entry = adapter.read(jsonReader); servers.add(entry); logger.info("Retrieved game server {}", entry); try { Thread.sleep(250); } catch (InterruptedException e) { // ignore - this is just to create an animation anyway } } jsonReader.endArray(); status = String.format("Server list complete"); } }
From source file:saulmm.avengers.model.rest.CharacterItemAdapterFactory.java
License:Mozilla Public License
@Override public <T> TypeAdapter<T> create(Gson gson, final TypeToken<T> type) { final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type); final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class); final TypeAdapter<T> customTypeAdapter = new TypeAdapter<T>() { @Override/*from w ww.j av a 2s . co m*/ public void write(JsonWriter out, T value) throws IOException { delegate.write(out, value); } @Override public T read(JsonReader in) throws IOException { JsonElement jsonElement = elementAdapter.read(in); if (type.getRawType() == saulmm.avengers.model.Character.class) return adaptJsonToCharacter(jsonElement, type); if (type.getRawType() == List.class) return adaptJsonToComic(jsonElement, type); return delegate.fromJsonTree(jsonElement); } }.nullSafe(); return customTypeAdapter; }
From source file:us.blanshard.sudoku.game.GameJson.java
License:Apache License
/** * Registers type adapters in the given builder so that history lists and undo * stacks can be serialized and deserialized. Note that undo stacks require a * CommandFactory be established before deserialization; see {@link #setFactory}. *//*from w w w . j a v a 2 s . c o m*/ public static GsonBuilder register(GsonBuilder builder) { builder.registerTypeHierarchyAdapter(Move.class, new TypeAdapter<Move>() { @Override public void write(JsonWriter out, Move value) throws IOException { out.value(value.toJsonValue()); } @Override public Move read(JsonReader in) throws IOException { return Move.fromJsonValue(in.nextString()); } }); final TypeAdapter<Command> commandAdapter = new TypeAdapter<Command>() { @Override public void write(JsonWriter out, Command value) throws IOException { out.value(value.toJsonValue()); } @Override public Command read(JsonReader in) throws IOException { Iterator<String> values = SPLITTER.split(in.nextString()).iterator(); String type = values.next(); return factorySlot.get().toCommand(type, values); } }; builder.registerTypeHierarchyAdapter(Command.class, commandAdapter); builder.registerTypeAdapter(UndoStack.class, new TypeAdapter<UndoStack>() { @Override public void write(JsonWriter out, UndoStack value) throws IOException { out.beginObject(); out.name("position").value(value.getPosition()); out.name("commands").beginArray(); for (Command c : value.commands) commandAdapter.write(out, c); out.endArray(); out.endObject(); } @Override public UndoStack read(JsonReader in) throws IOException { int position = -1; List<Command> commands = null; in.beginObject(); while (in.hasNext()) { String name = in.nextName(); if (name.equals("position")) { position = in.nextInt(); } else if (name.equals("commands")) { commands = Lists.newArrayList(); in.beginArray(); while (in.hasNext()) commands.add(commandAdapter.read(in)); in.endArray(); } else { in.skipValue(); } } in.endObject(); return new UndoStack(commands, position); } }); return builder; }