com.google.gson.stream.JsonWriter Java Examples

The following examples show how to use com.google.gson.stream.JsonWriter. 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: JsonLdSerializer.java    From schemaorg-java with Apache License 2.0 6 votes vote down vote up
private void writeReverse(JsonWriter out, ImmutableMultimap<String, Thing> map)
    throws IOException {
  Set<String> keySet = map.keySet();
  if (keySet.size() == 0) {
    return;
  }
  out.name(JsonLdConstants.REVERSE);
  out.beginObject();
  for (String key : keySet) {
    out.name(shortNameOf(key));
    Collection<Thing> values = map.get(key);
    if (values.size() == 0) {
      throw new JsonLdSyntaxException(
          String.format("JSON-LD reverse property %s has no value", key));
    } else if (values.size() == 1) {
      writeObject(out, (Thing) values.toArray()[0], false /* isTopLevelObject */);
    } else {
      out.beginArray();
      for (Thing value : values) {
        writeObject(out, value, false /* isTopLevelObject */);
      }
      out.endArray();
    }
  }
  out.endObject();
}
 
Example #2
Source File: SourceFileJsonTypeAdapter.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void write(JsonWriter out, SourceFile src) throws IOException {
    File file = src.getSourceFile();
    String description = src.getDescription();

    if (description == null && file != null) {
        out.value(file.getAbsolutePath());
        return;
    }

    out.beginObject();
    if (description != null) {
        out.name(DESCRIPTION).value(description);
    }
    if (file != null) {
        out.name(PATH).value(file.getAbsolutePath());
    }
    out.endObject();
}
 
Example #3
Source File: BaseTypeAdapter.java    From data-mediator with Apache License 2.0 6 votes vote down vote up
@Override
public void write(JsonWriter out, T obj) throws IOException {
    //log("BaseTypeAdapter_write");
    out.beginObject();
    for (GsonProperty prop : mProps) {
        Object val = SupportUtils.getValue(prop, obj);
        if (val == null) {
            continue;
        }
        //gson name
        out.name(prop.getRealSerializeName());

      //  log("simpleType = " + simpleType.getName());
        TypeHandler.getTypeHandler(prop).write(out, prop, val);
    }
    out.endObject();
}
 
Example #4
Source File: DefaultModule.java    From proteus with Apache License 2.0 6 votes vote down vote up
@Override
public CustomValueTypeAdapter<DrawableValue.ShapeValue> create(int type, final ProteusTypeAdapterFactory factory) {
  return new CustomValueTypeAdapter<DrawableValue.ShapeValue>(type) {
    @Override
    public void write(JsonWriter out, DrawableValue.ShapeValue value) throws IOException {
      // TODO: remove mock
      out.value("#00000000");
    }

    @Override
    public DrawableValue.ShapeValue read(JsonReader in) throws IOException {
      // TODO: remove mock
      in.skipValue();
      return DrawableValue.ShapeValue.valueOf(0, null, null);
    }
  };
}
 
Example #5
Source File: JsonRoutingTableSerializer.java    From Kademlia with MIT License 6 votes vote down vote up
@Override
public void write(KademliaRoutingTable data, DataOutputStream out) throws IOException
{
    try (JsonWriter writer = new JsonWriter(new OutputStreamWriter(out)))
    {
        writer.beginArray();

        /* Write the basic JKademliaRoutingTable */
        gson.toJson(data, JKademliaRoutingTable.class, writer);

        /* Now Store the Contacts  */
        gson.toJson(data.getAllContacts(), contactCollectionType, writer);

        writer.endArray();
    }
}
 
Example #6
Source File: ABIJSON.java    From headlong with Apache License 2.0 6 votes vote down vote up
private static void writeJsonArray(JsonWriter out, String name, TupleType tupleType, boolean[] indexedManifest) throws IOException {
    out.name(name).beginArray();
    for (int i = 0; i < tupleType.elementTypes.length; i++) {
        final ABIType<?> e = tupleType.elementTypes[i];
        out.beginObject();
        addIfValueNotNull(out, NAME, e.getName());
        out.name(TYPE);
        final String type = e.canonicalType;
        if(type.startsWith("(")) { // tuple
            out.value(type.replace(type.substring(0, type.lastIndexOf(')') + 1), TUPLE));
            ABIType<?> base = e;
            while (base instanceof ArrayType) {
                base = ((ArrayType<? extends ABIType<?>, ?>) base).elementType;
            }
            writeJsonArray(out, COMPONENTS, (TupleType) base, null);
        } else {
            out.value(type);
        }
        if(indexedManifest != null) {
            out.name(INDEXED).value(indexedManifest[i]);
        }
        out.endObject();
    }
    out.endArray();
}
 
Example #7
Source File: JSONHelper.java    From MercuryTrade with MIT License 5 votes vote down vote up
public void writeMapObject(String key, Map<?, ?> object) {
    try {
        Gson gson = new GsonBuilder().enableComplexMapKeySerialization().setPrettyPrinting().create();

        try (JsonWriter writer = new JsonWriter(new FileWriter(dataSource))) {
            JsonObject jsonObject = new JsonObject();
            jsonObject.add(key, gson.toJsonTree(object));
            gson.toJson(jsonObject, writer);
        }
    } catch (IOException e) {
        logger.error(e);
    }

}
 
Example #8
Source File: JSON.java    From android with MIT License 5 votes vote down vote up
@Override
public void write(JsonWriter out, Date date) throws IOException {
    if (date == null) {
        out.nullValue();
    } else {
        String value;
        if (dateFormat != null) {
            value = dateFormat.format(date);
        } else {
            value = ISO8601Utils.format(date, true);
        }
        out.value(value);
    }
}
 
Example #9
Source File: ParserHelper.java    From packagedrone with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void write ( final JsonWriter writer, final Version value ) throws IOException
{
    if ( value == null )
    {
        writer.nullValue ();
    }
    else
    {
        writer.value ( value.toString () );
    }
}
 
Example #10
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 #11
Source File: GeoJsonExporter.java    From TomboloDigitalConnector with MIT License 5 votes vote down vote up
private void writeFeatureForSubject(List<Field> fields, Subject subject, JsonWriter jsonWriter) throws IOException {
	jsonWriter.beginObject();

	jsonWriter.name("type").value("Feature");
	jsonWriter.name("geometry").jsonValue(getGeoJSONGeometryForSubject(subject));
	jsonWriter.name("properties").jsonValue(getPropertiesForSubject(fields, subject).toJSONString());

	jsonWriter.endObject();
}
 
Example #12
Source File: JSON.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Override
public void write(JsonWriter out, LocalDate date) throws IOException {
    if (date == null) {
        out.nullValue();
    } else {
        out.value(formatter.format(date));
    }
}
 
Example #13
Source File: UtcDateTypeAdapter.java    From gson with Apache License 2.0 5 votes vote down vote up
@Override
public void write(JsonWriter out, Date date) throws IOException {
  if (date == null) {
    out.nullValue();
  } else {
    String value = format(date, true, UTC_TIME_ZONE);
    out.value(value);
  }
}
 
Example #14
Source File: TypeAdapters.java    From framework with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void write(JsonWriter out, Class value) throws IOException {
  if (value == null) {
    out.nullValue();
  } else {
    throw new UnsupportedOperationException("Attempted to serialize java.lang.Class: "
        + value.getName() + ". Forgot to register a type adapter?");
  }
}
 
Example #15
Source File: CustomGsonRequestBodyConverter.java    From Retrofit2RxjavaDemo with Apache License 2.0 5 votes vote down vote up
@Override
public RequestBody convert(T value) throws IOException {
    Buffer buffer = new Buffer();
    Writer writer = new OutputStreamWriter(buffer.outputStream(), UTF_8);
    JsonWriter jsonWriter = gson.newJsonWriter(writer);
    adapter.write(jsonWriter, value);
    jsonWriter.close();
    return RequestBody.create(MEDIA_TYPE, buffer.readByteString());
}
 
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: NukkitRegistryDumper.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void write(final JsonWriter out, final Vector3 vec) throws IOException {
    out.beginArray();
    out.value(vec.getX());
    out.value(vec.getY());
    out.value(vec.getZ());
    out.endArray();
}
 
Example #18
Source File: CommandStub.java    From ForgeHax with MIT License 5 votes vote down vote up
@Override
public void serialize(JsonWriter writer) throws IOException {
  writer.beginObject();
  
  writer.name("bind");
  if (bind != null) {
    writer.value(bind.getKeyCode());
  } else {
    writer.value(-1);
  }
  
  writer.endObject();
}
 
Example #19
Source File: CQL2JSON.java    From cqlkit with Apache License 2.0 5 votes vote down vote up
@Override
public void writeHead() {
    if (commandLine.hasOption("a")) {
        try {
            jsonWriter = new JsonWriter(new OutputStreamWriter(System.out));
            jsonWriter.beginArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
 
Example #20
Source File: ChecksumAdapter.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void write(JsonWriter jsonWriter, Checksum checksum) throws IOException {
    if (checksum == null) {
        throw new JsonParseException("null is not a valid value for Checksum");
    }
    else {
        jsonWriter.value(checksum.toString());
    }
}
 
Example #21
Source File: CollectionTypeAdapterFactory.java    From letv with Apache License 2.0 5 votes vote down vote up
public void write(JsonWriter out, Collection<E> collection) throws IOException {
    if (collection == null) {
        out.nullValue();
        return;
    }
    out.beginArray();
    for (E element : collection) {
        this.elementTypeAdapter.write(out, element);
    }
    out.endArray();
}
 
Example #22
Source File: JsonAdapterAnnotationOnClassesTest.java    From gson with Apache License 2.0 5 votes vote down vote up
@Override public <T> TypeAdapter<T> create(Gson gson, final TypeToken<T> type) {
  return new TypeAdapter<T>() {
    @Override public void write(JsonWriter out, T value) throws IOException {
      out.value("jsonAdapterFactory");
    }
    @SuppressWarnings("unchecked")
    @Override public T read(JsonReader in) throws IOException {
      in.nextString();
      return (T) new C("jsonAdapterFactory");
    }
  };
}
 
Example #23
Source File: SpeechTimestampTypeAdapter.java    From java-sdk with Apache License 2.0 5 votes vote down vote up
@Override
public void write(JsonWriter writer, SpeechTimestamp speechTimestamp) throws IOException {
  writer.beginArray();

  writer.value(speechTimestamp.getWord());
  writer.value(speechTimestamp.getStartTime());
  writer.value(speechTimestamp.getEndTime());

  writer.endArray();
  writer.flush();
}
 
Example #24
Source File: JSON.java    From director-sdk with Apache License 2.0 5 votes vote down vote up
@Override
public void write(JsonWriter out, DateTime date) throws IOException {
    if (date == null) {
        out.nullValue();
    } else {
        out.value(date.getMillis());
    }
}
 
Example #25
Source File: Gson.java    From framework with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Writes out the equivalent JSON for a tree of {@link JsonElement}s.
 *
 * @param jsonElement root of a tree of {@link JsonElement}s
 * @param writer Writer to which the Json representation needs to be written
 * @throws JsonIOException if there was a problem writing to the writer
 * @since 1.4
 */
public void toJson(JsonElement jsonElement, Appendable writer) throws JsonIOException {
  try {
    JsonWriter jsonWriter = newJsonWriter(Streams.writerForAppendable(writer));
    toJson(jsonElement, jsonWriter);
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example #26
Source File: SemanticVersionTypeAdapter.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void write(JsonWriter out, SemanticVersion version) throws IOException {
    out.beginArray();
    out.value(version.major());
    out.value(version.minor());
    if(version.patch() != 0) out.value(version.patch());
    out.endArray();
}
 
Example #27
Source File: CategoriesTypeAdapter.java    From greenbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void write(JsonWriter writer, Categories categories) throws IOException {
	checkNotNull(categories);

	writer.beginObject();
	writer.name(NAME_CATEGORIES);
	writer.beginArray();
	for (Category category : categories.getCategories()) {
		writer.value(toEncryptedString(category));
	}
	writer.endArray();
	writer.endObject();
}
 
Example #28
Source File: Setting.java    From ForgeHax with MIT License 5 votes vote down vote up
@Override
public void serialize(JsonWriter writer) throws IOException {
  writer.beginObject();
  
  writer.name("value");
  writer.value(getAsString());
  
  writer.endObject();
}
 
Example #29
Source File: Pet.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
@Override
public void write(final JsonWriter jsonWriter, final StatusEnum enumeration) throws IOException {
  jsonWriter.value(enumeration.getValue());
}
 
Example #30
Source File: TypeAdapters.java    From gson with Apache License 2.0 4 votes vote down vote up
@Override
public void write(JsonWriter out, UUID value) throws IOException {
  out.value(value == null ? null : value.toString());
}