Java Code Examples for com.google.gson.TypeAdapter#write()

The following examples show how to use com.google.gson.TypeAdapter#write() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: IrisObjectTypeAdapter.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override public void write(JsonWriter out, Object value) throws IOException {
  if (value == null) {
    out.nullValue();
    return;
  }

  TypeAdapter<Object> typeAdapter = (TypeAdapter<Object>) gson.getAdapter(value.getClass());
  if (typeAdapter instanceof IrisObjectTypeAdapter) {
    out.beginObject();
    out.endObject();
    return;
  }

  typeAdapter.write(out, value);
}
 
Example 2
Source File: CollectionTypeAdapter.java    From lsp4j with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void write(JsonWriter out, Collection<E> collection) throws IOException {
	if (collection == null) {
		out.nullValue();
		return;
	}
	out.beginArray();
	for (E element : collection) {
		if (element != null && elementType != element.getClass()
				&& (elementType instanceof TypeVariable<?> || elementType instanceof Class<?>)) {
			@SuppressWarnings("unchecked")
			TypeAdapter<E> runtimeTypeAdapter = (TypeAdapter<E>) gson.getAdapter(TypeToken.get(element.getClass()));
			runtimeTypeAdapter.write(out, element);
		} else {
			elementTypeAdapter.write(out, element);
		}
	}
	out.endArray();
}
 
Example 3
Source File: ExpectedSubtypesAdapter.java    From immutables with Apache License 2.0 6 votes vote down vote up
@Override
public void write(JsonWriter out, T value) throws IOException {
  if (value == null) {
    out.nullValue();
    return;
  }
  for (int i = 0; i < subtypes.length; i++) {
    TypeToken<? extends T> subtype = subtypes[i];
    if (subtype.getRawType().isInstance(value)) {
      // safe unchecked, type is checked at runtime
      @SuppressWarnings("unchecked") TypeAdapter<Object> typeAdapter = (TypeAdapter<Object>) adapters.get(i);
      typeAdapter.write(out, value);
      return;
    }
  }
  gson.toJson(value, value.getClass(), out);
}
 
Example 4
Source File: ObjectTypeAdapter.java    From MiBandDecompiled with Apache License 2.0 6 votes vote down vote up
public void write(JsonWriter jsonwriter, Object obj)
{
    if (obj == null)
    {
        jsonwriter.nullValue();
        return;
    }
    TypeAdapter typeadapter = a.getAdapter(obj.getClass());
    if (typeadapter instanceof ObjectTypeAdapter)
    {
        jsonwriter.beginObject();
        jsonwriter.endObject();
        return;
    } else
    {
        typeadapter.write(jsonwriter, obj);
        return;
    }
}
 
Example 5
Source File: ObjectTypeAdapter.java    From framework with GNU Affero General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override public void write(JsonWriter out, Object value) throws IOException {
  if (value == null) {
    out.nullValue();
    return;
  }

  TypeAdapter<Object> typeAdapter = (TypeAdapter<Object>) gson.getAdapter(value.getClass());
  if (typeAdapter instanceof ObjectTypeAdapter) {
    out.beginObject();
    out.endObject();
    return;
  }

  typeAdapter.write(out, value);
}
 
Example 6
Source File: TypeHandler.java    From data-mediator with Apache License 2.0 6 votes vote down vote up
@Override
public void write(JsonWriter out,  GsonProperty property, Object value) throws IOException {
    final Class<?> simpleType = property.getType();
    out.beginObject();
    if(value != null) {
        final SparseArray sa = (SparseArray) value;
        if(simpleType.isPrimitive() || isBoxedClass(simpleType)){
            for (int size = sa.size(), i = size - 1; i >= 0; i--) {
                out.name(sa.keyAt(i) + "");
                writePrimitiveOrItsBox(out, simpleType, sa.valueAt(i));
            }
        }else {
            TypeAdapter adapter = getTypeAdapter(simpleType);
            for (int size = sa.size(), i = size - 1; i >= 0; i--) {
                out.name(sa.keyAt(i) + "");
                adapter.write(out, sa.valueAt(i));
            }
        }
    }
    out.endObject();
}
 
Example 7
Source File: TypeAdapters.java    From letv with Apache License 2.0 6 votes vote down vote up
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
    if (typeToken.getRawType() != Timestamp.class) {
        return null;
    }
    final TypeAdapter<Date> dateTypeAdapter = gson.getAdapter(Date.class);
    return new TypeAdapter<Timestamp>() {
        public Timestamp read(JsonReader in) throws IOException {
            Date date = (Date) dateTypeAdapter.read(in);
            return date != null ? new Timestamp(date.getTime()) : null;
        }

        public void write(JsonWriter out, Timestamp value) throws IOException {
            dateTypeAdapter.write(out, value);
        }
    };
}
 
Example 8
Source File: RequiredFieldTypeAdapterFactory.java    From plaid-java with MIT License 5 votes vote down vote up
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
  if (!type.getRawType().isAssignableFrom(RequiredField.class)) {
    return null;
  }

  final TypeAdapter delegateAdapter = gson.getAdapter(TypeToken.get(((ParameterizedType) type.getType()).getActualTypeArguments()[0]));

  return new TypeAdapter<T>() {
    @Override
    @SuppressWarnings({"unchecked", "rawtypes"})
    public void write(JsonWriter out, T value) throws IOException {
      RequiredField requiredField = (RequiredField) value;

      if (requiredField == null || !requiredField.isPresent()) {
        boolean oldSerializeNulls = out.getSerializeNulls();
        out.setSerializeNulls(true);
        out.nullValue();
        out.setSerializeNulls(oldSerializeNulls);
      } else {
        delegateAdapter.write(out, requiredField.get());
      }
    }

    @Override
    @SuppressWarnings("unchecked")
    public T read(JsonReader reader) throws IOException {
      return (T) RequiredField.of(delegateAdapter.read(reader));
    }
  };
}
 
Example 9
Source File: TypeAdapterRuntimeTypeWrapper.java    From framework with GNU Affero General Public License v3.0 5 votes vote down vote up
@SuppressWarnings({"rawtypes", "unchecked"})
@Override
public void write(JsonWriter out, T value) throws IOException {
  // Order of preference for choosing type adapters
  // First preference: a type adapter registered for the runtime type
  // Second preference: a type adapter registered for the declared type
  // Third preference: reflective type adapter for the runtime type (if it is a sub class of the declared type)
  // Fourth preference: reflective type adapter for the declared type

  TypeAdapter chosen = delegate;
  Type runtimeType = getRuntimeTypeIfMoreSpecific(type, value);
  if (runtimeType != type) {
    TypeAdapter runtimeTypeAdapter = context.getAdapter(TypeToken.get(runtimeType));
    if (!(runtimeTypeAdapter instanceof ReflectiveTypeAdapterFactory.Adapter)) {
      // The user registered a type adapter for the runtime type, so we will use that
      chosen = runtimeTypeAdapter;
    } else if (!(delegate instanceof ReflectiveTypeAdapterFactory.Adapter)) {
      // The user registered a type adapter for Base class, so we prefer it over the
      // reflective type adapter for the runtime type
      chosen = delegate;
    } else {
      // Use the type adapter for runtime type
      chosen = runtimeTypeAdapter;
    }
  }
  chosen.write(out, value);
}
 
Example 10
Source File: JavaTimeTest.java    From immutables with Apache License 2.0 5 votes vote down vote up
private <T> BsonValue writeAndReadBson(T value) throws IOException {
  TypeAdapter<T> adapter = gson.getAdapter((Class<T>) value.getClass());
  BsonDocumentWriter writer = new BsonDocumentWriter(new BsonDocument());
  writer.writeStartDocument();
  writer.writeName("value");
  adapter.write(Jsons.asGsonWriter(writer), value);
  writer.writeEndDocument();

  BsonValue bson = writer.getDocument().get("value");
  check(bson).notNull();
  return bson;
}
 
Example 11
Source File: ResultTypeAdapterFactory.java    From salt-netapi-client with MIT License 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
private TypeAdapter<Result> wrap(TypeAdapter<Xor> xorTypeAdapter) {
    return new TypeAdapter<Result>() {
        @Override
        public Result read(JsonReader in) throws IOException {
            return new Result(xorTypeAdapter.read(in));
        }

        @Override
        public void write(JsonWriter out, Result result) throws IOException {
            xorTypeAdapter.write(out, result.toXor());
        }
    };
}
 
Example 12
Source File: TypeAdapterRuntimeTypeWrapper.java    From letv with Apache License 2.0 5 votes vote down vote up
public void write(JsonWriter out, T value) throws IOException {
    TypeAdapter chosen = this.delegate;
    Type runtimeType = getRuntimeTypeIfMoreSpecific(this.type, value);
    if (runtimeType != this.type) {
        TypeAdapter runtimeTypeAdapter = this.context.getAdapter(TypeToken.get(runtimeType));
        if (!(runtimeTypeAdapter instanceof Adapter)) {
            chosen = runtimeTypeAdapter;
        } else if (this.delegate instanceof Adapter) {
            chosen = runtimeTypeAdapter;
        } else {
            chosen = this.delegate;
        }
    }
    chosen.write(out, value);
}
 
Example 13
Source File: MapTypeAdapterFactory.java    From letv with Apache License 2.0 5 votes vote down vote up
private static <T> JsonElement toJsonTree(TypeAdapter<T> typeAdapter, T value) {
    try {
        JsonTreeWriter jsonWriter = new JsonTreeWriter();
        jsonWriter.setLenient(true);
        typeAdapter.write(jsonWriter, value);
        return jsonWriter.get();
    } catch (Throwable e) {
        throw new JsonIOException(e);
    }
}
 
Example 14
Source File: ObjectTypeAdapter.java    From letv with Apache License 2.0 5 votes vote down vote up
public void write(JsonWriter out, Object value) throws IOException {
    if (value == null) {
        out.nullValue();
        return;
    }
    TypeAdapter<Object> typeAdapter = this.gson.getAdapter(value.getClass());
    if (typeAdapter instanceof ObjectTypeAdapter) {
        out.beginObject();
        out.endObject();
        return;
    }
    typeAdapter.write(out, value);
}
 
Example 15
Source File: UrlEncodedGsonRequestBodyConverter.java    From proteus with Apache License 2.0 5 votes vote down vote up
@Override
public RequestBody convert(T value) throws IOException {
  //noinspection unchecked
  TypeAdapter<T> adapter = (TypeAdapter<T>) gson.getAdapter(TypeToken.get(type));
  Writer writer = new StringWriter();
  JsonWriter jsonWriter = gson.newJsonWriter(writer);
  adapter.write(jsonWriter, value);
  jsonWriter.close();
  return RequestBody.create(MEDIA_TYPE, URLEncoder.encode(writer.toString(), "UTF-8").getBytes());
}
 
Example 16
Source File: OptionalTypeAdapterFactory.java    From plaid-java with MIT License 5 votes vote down vote up
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
  if (!Optional.class.isAssignableFrom(type.getRawType())) {
    return null;
  }

  final TypeAdapter delegateAdapter = gson.getAdapter(TypeToken.get(((ParameterizedType) type.getType()).getActualTypeArguments()[0]));

  return new TypeAdapter<T>() {
    @Override
    @SuppressWarnings({"unchecked", "rawtypes"})
    public void write(JsonWriter out, T value) throws IOException {
      if (((Optional) value).isPresent()) {
        delegateAdapter.write(out, ((Optional) value).get());
      } else {
        out.nullValue();
      }
    }

    @Override
    @SuppressWarnings("unchecked")
    public T read(JsonReader in) throws IOException {
      Object readObject = delegateAdapter.read(in);
      if (readObject == null) {
        return (T) Optional.empty();
      } else {
        return (T) Optional.of(readObject);
      }
    }
  };
}
 
Example 17
Source File: OptionalTypeAdapterFactory.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
private <A> TypeAdapter<Optional<A>> optionalAdapter(TypeAdapter<A> innerAdapter) {
    return new TypeAdapter<Optional<A>>() {
        @Override
        public Optional<A> read(JsonReader in) throws IOException {
            if (in.peek() == JsonToken.NULL) {
                in.nextNull();
                return Optional.empty();
            }
            else {
                JsonElement json = TypeAdapters.JSON_ELEMENT.read(in);
                try {
                    A value = innerAdapter.fromJsonTree(json);
                    return Optional.of(value);
                }
                catch (JsonSyntaxException e) {
                    /**
                     * Note : This is a workaround and it only exists because salt doesn't differentiate between a
                     * non-existent grain and a grain which exists but has value set to empty String.
                     *
                     * If an object is expected but instead empty string comes in then we return empty Optional.
                     */
                    if (json.isJsonPrimitive() && json.getAsJsonPrimitive().isString() &&
                            json.getAsString().isEmpty()) {
                        return Optional.empty();
                    }
                    throw e;
                }
            }
        }

        @Override
        public void write(JsonWriter out, Optional<A> optional) throws IOException {
            innerAdapter.write(out, optional.orElse(null));
        }
    };
}
 
Example 18
Source File: ProblemAdapterFactory.java    From problem with MIT License 4 votes vote down vote up
@Override
public void write(final JsonWriter out, final T value) throws IOException {
    final TypeAdapter<T> adapter = selectAdapter(value);
    adapter.write(out, value);
}
 
Example 19
Source File: GeometryCollection.java    From mapbox-java with MIT License 4 votes vote down vote up
@Override
public void write(JsonWriter jsonWriter, GeometryCollection object) throws IOException {
  if (object == null) {
    jsonWriter.nullValue();
    return;
  }
  jsonWriter.beginObject();
  jsonWriter.name("type");
  if (object.type() == null) {
    jsonWriter.nullValue();
  } else {
    TypeAdapter<String> stringTypeAdapter = this.stringTypeAdapter;
    if (stringTypeAdapter == null) {
      stringTypeAdapter = gson.getAdapter(String.class);
      this.stringTypeAdapter = stringTypeAdapter;
    }
    stringTypeAdapter.write(jsonWriter, object.type());
  }
  jsonWriter.name("bbox");
  if (object.bbox() == null) {
    jsonWriter.nullValue();
  } else {
    TypeAdapter<BoundingBox> boundingBoxTypeAdapter = this.boundingBoxTypeAdapter;
    if (boundingBoxTypeAdapter == null) {
      boundingBoxTypeAdapter = gson.getAdapter(BoundingBox.class);
      this.boundingBoxTypeAdapter = boundingBoxTypeAdapter;
    }
    boundingBoxTypeAdapter.write(jsonWriter, object.bbox());
  }
  jsonWriter.name("geometries");
  if (object.geometries() == null) {
    jsonWriter.nullValue();
  } else {
    TypeAdapter<List<Geometry>> listGeometryAdapter = this.listGeometryAdapter;
    if (listGeometryAdapter == null) {
      TypeToken typeToken = TypeToken.getParameterized(List.class, Geometry.class);
      listGeometryAdapter =
              (TypeAdapter<List<Geometry>>) gson.getAdapter(typeToken);
      this.listGeometryAdapter = listGeometryAdapter;
    }
    listGeometryAdapter.write(jsonWriter, object.geometries());
  }
  jsonWriter.endObject();
}
 
Example 20
Source File: HarvesterAnimationStateMachine.java    From EmergingTechnology with MIT License 4 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
@Nullable
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    if (type.getRawType() != ImmutableMultimap.class || !(type.getType() instanceof ParameterizedType)) {
        return null;
    }
    final Type[] typeArguments = ((ParameterizedType) type.getType()).getActualTypeArguments();
    if (typeArguments.length != 2 || typeArguments[0] != String.class || typeArguments[1] != String.class) {
        return null;
    }
    final TypeAdapter<Map<String, Collection<String>>> mapAdapter = gson
            .getAdapter(new TypeToken<Map<String, Collection<String>>>() {
            });
    final TypeAdapter<Collection<String>> collectionAdapter = gson
            .getAdapter(new TypeToken<Collection<String>>() {
            });
    return (TypeAdapter<T>) new TypeAdapter<ImmutableMultimap<String, String>>() {
        @Override
        public void write(JsonWriter out, ImmutableMultimap<String, String> value) throws IOException {
            mapAdapter.write(out, value.asMap());
        }

        @Override
        public ImmutableMultimap<String, String> read(JsonReader in) throws IOException {
            ImmutableMultimap.Builder<String, String> builder = ImmutableMultimap.builder();
            in.beginObject();
            while (in.hasNext()) {
                String key = in.nextName();
                switch (in.peek()) {
                    case STRING:
                        builder.put(key, in.nextString());
                        break;
                    case BEGIN_ARRAY:
                        builder.putAll(key, collectionAdapter.read(in));
                        break;
                    default:
                        throw new JsonParseException("Expected String or Array, got " + in.peek());
                }
            }
            in.endObject();
            return builder.build();
        }
    };
}