List of usage examples for com.google.gson TypeAdapter write
public abstract void write(JsonWriter out, T value) throws IOException;
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// w w w . ja v a 2 s .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/*ww w .j a v a 2s . 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 a va2s.c o m 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 va 2s . c o m public void write(JsonWriter out, Object value) throws IOException { if (value == null) { out.nullValue(); return; } out.beginObject(); try { boolean setType = true; if ((metadataAccess != null) && (metadataAccess.fieldName != null)) { if (metadataAccess.getter == null) { //TODO throw new AssertionError(); } Object metadata = metadataAccess.getter.invoke(value); BoundField metadataField = boundFields.get(metadataAccess.fieldName); if (metadataField != null && metadata != null) { Map<String, BoundField> metaBoundFields = null; if (!Map.class.isAssignableFrom(metadata.getClass())) { metaBoundFields = reflectiveFactory.getBoundFields(gson, metadataField.type, metadataField.type.getRawType()); } if (metaBoundFields != null) { for (BoundField boundField : metaBoundFields.values()) { if (boundField.serialized) { out.name(Constants.META_CHAR.concat(boundField.name)); boundField.write(out, metadata); if (setType) { setType = !"profile".equals(boundField.name); } } } } else { Map values = (Map) metadata; for (Object key : values.keySet()) { Object v = values.get(key); if (v != null) { out.name(Constants.META_CHAR.concat(key.toString())); TypeAdapter ta = gson.getAdapter(v.getClass()); ta.write(out, v); } } } } } if (setType && (metadataAccess != null) && (metadataAccess.profile != null) && (metadataAccess.profile.length > 0)) { out.name(Constants.META_CHAR.concat("profile")); out.beginArray(); for (String profile : metadataAccess.profile) { out.value(profile); } out.endArray(); } for (BoundField boundField : boundFields.values()) { if (boundField.serialized && !boundField.name.equals(metadataAccess.fieldName)) { out.name(boundField.name); boundField.write(out, value); } } } catch (IllegalAccessException e) { throw new AssertionError(); } catch (IllegalArgumentException e) { throw new AssertionError(); } catch (InvocationTargetException e) { throw new AssertionError(); } out.endObject(); }
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 . ja v 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 . jav a 2s. com 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; }