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 Project: Kademlia   Author: JoshuaKissoon   File: JsonRoutingTableSerializer.java    License: 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 #2
Source Project: javaide   Author: tranleduy2000   File: SourceFileJsonTypeAdapter.java    License: 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 Project: schemaorg-java   Author: google   File: JsonLdSerializer.java    License: 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 #4
Source Project: data-mediator   Author: LightSun   File: BaseTypeAdapter.java    License: 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 #5
Source Project: proteus   Author: flipkart-incubator   File: DefaultModule.java    License: 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 #6
Source Project: headlong   Author: esaulpaugh   File: ABIJSON.java    License: 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 Project: gson   Author: google   File: UtcDateTypeAdapter.java    License: 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 #8
Source Project: ForgeHax   Author: fr1kin   File: Setting.java    License: 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 #9
Source Project: greenbeans   Author: greensopinion   File: CategoriesTypeAdapter.java    License: 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 #10
Source Project: director-sdk   Author: cloudera   File: JSON.java    License: 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 #11
Source Project: java-sdk   Author: watson-developer-cloud   File: SpeechTimestampTypeAdapter.java    License: 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 #12
Source Project: gson   Author: google   File: JsonAdapterAnnotationOnClassesTest.java    License: 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 #13
Source Project: cqlkit   Author: tenmax   File: CQL2JSON.java    License: 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 #14
Source Project: openapi-generator   Author: OpenAPITools   File: JSON.java    License: 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 #15
Source Project: framework   Author: Odoo-mobile   File: TypeAdapters.java    License: 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 #16
Source Project: plaid-java   Author: plaid   File: OptionalTypeAdapterFactory.java    License: 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 Project: MercuryTrade   Author: Exslims   File: JSONHelper.java    License: 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 #18
Source Project: TomboloDigitalConnector   Author: FutureCitiesCatapult   File: GeoJsonExporter.java    License: 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 #19
Source Project: ForgeHax   Author: fr1kin   File: CommandStub.java    License: 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 #20
Source Project: Retrofit2RxjavaDemo   Author: ysmintor   File: CustomGsonRequestBodyConverter.java    License: 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 #21
Source Project: framework   Author: Odoo-mobile   File: TypeAdapterRuntimeTypeWrapper.java    License: 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 #22
Source Project: packagedrone   Author: eclipse   File: ParserHelper.java    License: 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 #23
Source Project: android   Author: gotify   File: JSON.java    License: 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 #24
Source Project: FastAsyncWorldedit   Author: boy0001   File: NukkitRegistryDumper.java    License: 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 #25
Source Project: uyuni   Author: uyuni-project   File: ChecksumAdapter.java    License: 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 #26
Source Project: letv   Author: JackChan1999   File: CollectionTypeAdapterFactory.java    License: 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 #27
Source Project: framework   Author: Odoo-mobile   File: Gson.java    License: 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 #28
Source Project: ProjectAres   Author: OvercastNetwork   File: SemanticVersionTypeAdapter.java    License: 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 #29
Source Project: director-sdk   Author: cloudera   File: InstanceState.java    License: 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 Project: feign   Author: OpenFeign   File: DoubleToIntMapTypeAdapter.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void write(JsonWriter out, Map<String, Object> value) throws IOException {
  delegate.write(out, value);
}