Пример #1
0
  @Override
  public void write(JsonWriter out, Patch<Data> value) throws IOException {
    JsonTreeWriter treeWriter = new JsonTreeWriter();
    treeWriter.setSerializeNulls(true);
    _dataAdapter.write(treeWriter, value.data());
    JsonObject tree = treeWriter.get().getAsJsonObject();

    Set<String> presentJsonProperties = new HashSet<>();
    for (Field field : value.changedFields()) {
      SerializedName nameSpecifier = field.getAnnotation(SerializedName.class);
      String jsonPropertyName = (nameSpecifier != null ? nameSpecifier.value() : field.getName());
      presentJsonProperties.add(jsonPropertyName);
    }

    for (Map.Entry<String, JsonElement> entry : new ArrayList<>(tree.entrySet())) {
      if (!presentJsonProperties.contains(entry.getKey())) {
        tree.remove(entry.getKey());
      }
    }

    // If a data field changed to null the null should be serialized.
    // This is the whole point of this adapter.
    ObjectTargetedJsonWriter patchWriter = new ObjectTargetedJsonWriter(out);
    patchWriter.setTargetedSerializeNulls(true);
    _gson.getAdapter(JsonObject.class).write(patchWriter, tree);
  }
Пример #2
0
 /**
  * Converts {@code value} to a JSON tree.
  *
  * @param value the Java object to convert. May be null.
  * @return the converted JSON tree. May be {@link JsonNull}.
  * @since 2.2
  */
 public final JsonElement toJsonTree(T value) {
   try {
     JsonTreeWriter jsonWriter = new JsonTreeWriter();
     write(jsonWriter, value);
     return jsonWriter.get();
   } catch (IOException e) {
     throw new JsonIOException(e);
   }
 }
Пример #3
0
 public JsonElement toJsonTree(Object paramObject, Type paramType) {
   JsonTreeWriter localJsonTreeWriter = new JsonTreeWriter();
   toJson(paramObject, paramType, localJsonTreeWriter);
   return localJsonTreeWriter.get();
 }