Java Code Examples for com.google.gson.stream.JsonWriter#setIndent()

The following examples show how to use com.google.gson.stream.JsonWriter#setIndent() . 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: JsonCodec.java    From denominator with Apache License 2.0 6 votes vote down vote up
<T> MockResponse toJsonArray(Iterator<T> elements) {
  elements.hasNext(); // defensive to make certain error cases eager.

  StringWriter out = new StringWriter(); // MWS cannot do streaming responses.
  try {
    JsonWriter writer = new JsonWriter(out);
    writer.setIndent("  ");
    writer.beginArray();
    while (elements.hasNext()) {
      Object next = elements.next();
      json.toJson(next, next.getClass(), writer);
    }
    writer.endArray();
    writer.flush();
  } catch (IOException e) {
    throw new RuntimeException(e);
  }

  return new MockResponse().setResponseCode(200)
      .addHeader("Content-Type", "application/json")
      .setBody(out.toString() + "\n"); // curl nice
}
 
Example 2
Source File: Gson.java    From MiBandDecompiled with Apache License 2.0 5 votes vote down vote up
private JsonWriter a(Writer writer)
{
    if (k)
    {
        writer.write(")]}'\n");
    }
    JsonWriter jsonwriter = new JsonWriter(writer);
    if (l)
    {
        jsonwriter.setIndent("  ");
    }
    jsonwriter.setSerializeNulls(i);
    return jsonwriter;
}
 
Example 3
Source File: JsonRenderer.java    From js-dossier with Apache License 2.0 5 votes vote down vote up
private void render(Writer writer, JsonElement json) throws IOException {
  JsonWriter jsonWriter = new JsonWriter(writer);
  jsonWriter.setLenient(false);
  jsonWriter.setIndent("");
  jsonWriter.setSerializeNulls(false);
  Streams.write(json, jsonWriter);
}
 
Example 4
Source File: Profiler.java    From bazel with Apache License 2.0 5 votes vote down vote up
private void writeTask(JsonWriter writer, TaskData data) throws IOException {
  Preconditions.checkNotNull(data);
  String eventType = data.duration == 0 ? "i" : "X";
  writer.setIndent("  ");
  writer.beginObject();
  writer.setIndent("");
  if (data.type == null) {
    writer.setIndent("    ");
  } else {
    writer.name("cat").value(data.type.description);
  }
  writer.name("name").value(data.description);
  writer.name("ph").value(eventType);
  writer
      .name("ts")
      .value(TimeUnit.NANOSECONDS.toMicros(data.startTimeNanos - profileStartTimeNanos));
  if (data.duration != 0) {
    writer.name("dur").value(TimeUnit.NANOSECONDS.toMicros(data.duration));
  }
  writer.name("pid").value(1);

  // Primary outputs are non-mergeable, thus incompatible with slim profiles.
  if (includePrimaryOutput && data instanceof ActionTaskData) {
    writer.name("out").value(((ActionTaskData) data).primaryOutputPath);
  }
  if (includeTargetLabel && data instanceof ActionTaskData) {
    writer.name("args");
    writer.beginObject();
    writer.name("target").value(((ActionTaskData) data).targetLabel);
    writer.endObject();
  }
  long threadId =
      data.type == ProfilerTask.CRITICAL_PATH_COMPONENT
          ? CRITICAL_PATH_THREAD_ID
          : data.threadId;
  writer.name("tid").value(threadId);
  writer.endObject();
}
 
Example 5
Source File: Gson.java    From framework with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Returns a new JSON writer configured for this GSON and with the non-execute
 * prefix if that is configured.
 */
private JsonWriter newJsonWriter(Writer writer) throws IOException {
  if (generateNonExecutableJson) {
    writer.write(JSON_NON_EXECUTABLE_PREFIX);
  }
  JsonWriter jsonWriter = new JsonWriter(writer);
  if (prettyPrinting) {
    jsonWriter.setIndent("  ");
  }
  jsonWriter.setSerializeNulls(serializeNulls);
  return jsonWriter;
}
 
Example 6
Source File: MixedStreamTest.java    From gson with Apache License 2.0 5 votes vote down vote up
public void testWriteMixedStreamed() throws IOException {
  Gson gson = new Gson();
  StringWriter stringWriter = new StringWriter();
  JsonWriter jsonWriter = new JsonWriter(stringWriter);

  jsonWriter.beginArray();
  jsonWriter.setIndent("  ");
  gson.toJson(BLUE_MUSTANG, Car.class, jsonWriter);
  gson.toJson(BLACK_BMW, Car.class, jsonWriter);
  gson.toJson(RED_MIATA, Car.class, jsonWriter);
  jsonWriter.endArray();

  assertEquals(CARS_JSON, stringWriter.toString());
}
 
Example 7
Source File: Gson.java    From gson with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new JSON writer configured for the settings on this Gson instance.
 */
public JsonWriter newJsonWriter(Writer writer) throws IOException {
  if (generateNonExecutableJson) {
    writer.write(JSON_NON_EXECUTABLE_PREFIX);
  }
  JsonWriter jsonWriter = new JsonWriter(writer);
  if (prettyPrinting) {
    jsonWriter.setIndent("  ");
  }
  jsonWriter.setSerializeNulls(serializeNulls);
  return jsonWriter;
}
 
Example 8
Source File: GsonPlacesApiJsonParser.java    From android-PlacesAutocompleteTextView with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void writeHistoryJson(final OutputStream os, final List<Place> places) throws JsonWritingException {
    try {
        JsonWriter writer = new JsonWriter(new OutputStreamWriter(os, "UTF-8"));
        writer.setIndent("  ");
        writer.beginArray();
        for (Place place : places) {
            gson.toJson(place, Place.class, writer);
        }
        writer.endArray();
        writer.close();
    } catch (Exception e) {
        throw new JsonWritingException(e);
    }
}
 
Example 9
Source File: JsonSerializer.java    From incubator-atlas with Apache License 2.0 5 votes vote down vote up
public String serialize(Result result, UriInfo ui) {
    Writer json = new StringWriter();
    JsonWriter writer = new JsonWriter(json);
    writer.setIndent("    ");

    try {
        writeValue(writer, result.getPropertyMaps(), ui.getBaseUri().toASCIIString());
    } catch (IOException e) {
        throw new CatalogRuntimeException("Unable to write JSON response.", e);
    }
    return json.toString();
}
 
Example 10
Source File: EmployeeGsonWriter.java    From journaldev with MIT License 5 votes vote down vote up
public static void main(String[] args) throws IOException {
	Employee emp = EmployeeGsonExample.createEmployee();
	
	//writing on console, we can initialize with FileOutputStream to write to file
	OutputStreamWriter out = new OutputStreamWriter(System.out);
	JsonWriter writer = new JsonWriter(out);
	//set indentation for pretty print
	writer.setIndent("\t");
	//start writing
	writer.beginObject(); //{
	writer.name("id").value(emp.getId()); // "id": 123
	writer.name("name").value(emp.getName()); // "name": "David"
	writer.name("permanent").value(emp.isPermanent()); // "permanent": false
	writer.name("address").beginObject(); // "address": {
		writer.name("street").value(emp.getAddress().getStreet()); // "street": "BTM 1st Stage"
		writer.name("city").value(emp.getAddress().getCity()); // "city": "Bangalore"
		writer.name("zipcode").value(emp.getAddress().getZipcode()); // "zipcode": 560100
		writer.endObject(); // }
	writer.name("phoneNumbers").beginArray(); // "phoneNumbers": [
		for(long num : emp.getPhoneNumbers()) writer.value(num); //123456,987654
		writer.endArray(); // ]
	writer.name("role").value(emp.getRole()); // "role": "Manager"
	writer.name("cities").beginArray(); // "cities": [
		for(String c : emp.getCities()) writer.value(c); //"Los Angeles","New York"
		writer.endArray(); // ]
	writer.name("properties").beginObject(); //"properties": {
		Set<String> keySet = emp.getProperties().keySet();
		for(String key : keySet) writer.name("key").value(emp.getProperties().get(key));//"age": "28 years","salary": "1000 Rs"
		writer.endObject(); // }
	writer.endObject(); // }
	
	writer.flush();
	
	//close writer
	writer.close();
	
}
 
Example 11
Source File: PeerSaver.java    From MakeLobbiesGreatAgain with MIT License 5 votes vote down vote up
private void savePeers(OutputStream out, List<IOPeer> peers) throws IOException {
	Gson gson = new Gson();
	JsonWriter writer = new JsonWriter(new OutputStreamWriter(out, "UTF-8"));
	writer.setIndent("");
	writer.beginArray();
	peers.forEach(p -> {
		gson.toJson(p, IOPeer.class, writer);
		p.saved = true;
	});
	writer.endArray();
	writer.close();
}
 
Example 12
Source File: ReportExporter.java    From synthea with Apache License 2.0 5 votes vote down vote up
/**
 * Export the outcomes, access, and cost report. Requires a Generator with a
 * database. If the database is null, this method will return immediately.
 * In order for a database to be present in the generator, the Synthea
 * configuration file (synthea.properties) should have the `generate.database_type`
 * property set to `file` or `in-memory`.
 * This report will be written to the output folder, in a `statistics` folder, in a file
 * named `statistics-{timestamp}.json`.
 * @param generator - Generator with a database.
 */
public static void export(Generator generator) {
  if (generator == null || generator.database == null) {
    return;
  }

  try (Connection connection = generator.database.getConnection()) {
    File outDirectory = Exporter.getOutputFolder("statistics", null);
    String timeStamp = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(new Date());
    Path outFilePath = outDirectory.toPath().resolve("statistics-" + timeStamp + ".json");

    JsonWriter writer = new JsonWriter(new OutputStreamWriter(
        new FileOutputStream(outFilePath.toFile()), charset));
    writer.setIndent("  ");
    writer.beginObject(); // top-level

    reportParameters(writer);
    processOutcomes(connection, writer);
    processAccess(connection, writer);
    processCosts(connection, writer);

    writer.endObject(); // top-level
    writer.close();

  } catch (IOException | SQLException e) {
    e.printStackTrace();
    throw new RuntimeException("error exporting statistics");
  }
}
 
Example 13
Source File: GsonSmartyStreetsApiJsonParser.java    From Smarty-Streets-AutoCompleteTextView with Apache License 2.0 5 votes vote down vote up
@Override
public void writeHistoryJson(final OutputStream os, final List<Address> addresses) throws JsonWritingException {
    try {
        JsonWriter writer = new JsonWriter(new OutputStreamWriter(os, "UTF-8"));
        writer.setIndent("  ");
        writer.beginArray();
        for (Address address : addresses) {
            gson.toJson(address, Address.class, writer);
        }
        writer.endArray();
        writer.close();
    } catch (Exception e) {
        throw new JsonWritingException(e);
    }
}
 
Example 14
Source File: Gson.java    From letv with Apache License 2.0 5 votes vote down vote up
private JsonWriter newJsonWriter(Writer writer) throws IOException {
    if (this.generateNonExecutableJson) {
        writer.write(JSON_NON_EXECUTABLE_PREFIX);
    }
    JsonWriter jsonWriter = new JsonWriter(writer);
    if (this.prettyPrinting) {
        jsonWriter.setIndent("  ");
    }
    jsonWriter.setSerializeNulls(this.serializeNulls);
    return jsonWriter;
}
 
Example 15
Source File: JsonUtil.java    From java-trader with Apache License 2.0 5 votes vote down vote up
public static String json2str(JsonElement json, Boolean pretty) {
   try {
       StringWriter stringWriter = new StringWriter(1024);
        JsonWriter jsonWriter = new JsonWriter(stringWriter);
        if ( pretty!=null && pretty ) {
            jsonWriter.setIndent("  ");
        }
        jsonWriter.setLenient(true);
        Streams.write(json, jsonWriter);
        return stringWriter.toString();
   }catch(Throwable t) {
       return json.toString();
   }
}
 
Example 16
Source File: ZooKeeperMigrator.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
void readZooKeeper(OutputStream zkData, AuthMode authMode, byte[] authData) throws IOException, KeeperException, InterruptedException, ExecutionException {
    ZooKeeper zooKeeper = getZooKeeper(zooKeeperEndpointConfig.getConnectString(), authMode, authData);
    JsonWriter jsonWriter = new JsonWriter(new BufferedWriter(new OutputStreamWriter(zkData)));
    jsonWriter.setIndent("  ");
    JsonParser jsonParser = new JsonParser();
    Gson gson = new GsonBuilder().create();

    jsonWriter.beginArray();

    // persist source ZooKeeperEndpointConfig
    gson.toJson(jsonParser.parse(gson.toJson(zooKeeperEndpointConfig)).getAsJsonObject(), jsonWriter);

    LOGGER.info("Retrieving data from source ZooKeeper: {}", zooKeeperEndpointConfig);
    final List<CompletableFuture<Void>> readFutures = streamPaths(getNode(zooKeeper, "/"))
            .parallel()
            .map(node ->
                    CompletableFuture.supplyAsync(() -> {
                        final DataStatAclNode dataStatAclNode = retrieveNode(zooKeeper, node);
                        LOGGER.debug("retrieved node {} from {}", dataStatAclNode, zooKeeperEndpointConfig);
                        return dataStatAclNode;
                    }).thenAccept(dataStatAclNode -> {
                        // persist each zookeeper node
                        synchronized (jsonWriter) {
                            gson.toJson(jsonParser.parse(gson.toJson(dataStatAclNode)).getAsJsonObject(), jsonWriter);
                        }
                    })
            ).collect(Collectors.toList());

    CompletableFuture<Void> allReadsFuture = CompletableFuture.allOf(readFutures.toArray(new CompletableFuture[readFutures.size()]));
    final CompletableFuture<List<Void>> finishedReads = allReadsFuture
            .thenApply(v -> readFutures.stream()
                    .map(CompletableFuture::join)
                    .collect(Collectors.toList()));
    final List<Void> readsDone = finishedReads.get();
    jsonWriter.endArray();
    jsonWriter.close();
    if (LOGGER.isInfoEnabled()) {
        final int readCount = readsDone.size();
        LOGGER.info("{} {} read from {}", readCount, readCount == 1 ? "node" : "nodes", zooKeeperEndpointConfig);
    }
    closeZooKeeper(zooKeeper);
}
 
Example 17
Source File: ZooKeeperMigrator.java    From nifi with Apache License 2.0 4 votes vote down vote up
void readZooKeeper(OutputStream zkData, AuthMode authMode, byte[] authData) throws IOException, KeeperException, InterruptedException, ExecutionException {
    ZooKeeper zooKeeper = getZooKeeper(zooKeeperEndpointConfig.getConnectString(), authMode, authData);
    JsonWriter jsonWriter = new JsonWriter(new BufferedWriter(new OutputStreamWriter(zkData)));
    jsonWriter.setIndent("  ");
    JsonParser jsonParser = new JsonParser();
    Gson gson = new GsonBuilder().create();

    jsonWriter.beginArray();

    // persist source ZooKeeperEndpointConfig
    gson.toJson(jsonParser.parse(gson.toJson(zooKeeperEndpointConfig)).getAsJsonObject(), jsonWriter);

    LOGGER.info("Retrieving data from source ZooKeeper: {}", zooKeeperEndpointConfig);
    final List<CompletableFuture<Void>> readFutures = streamPaths(getNode(zooKeeper, "/"))
            .parallel()
            .map(node ->
                    CompletableFuture.supplyAsync(() -> {
                        final DataStatAclNode dataStatAclNode = retrieveNode(zooKeeper, node);
                        LOGGER.debug("retrieved node {} from {}", dataStatAclNode, zooKeeperEndpointConfig);
                        return dataStatAclNode;
                    }).thenAccept(dataStatAclNode -> {
                        // persist each zookeeper node
                        synchronized (jsonWriter) {
                            gson.toJson(jsonParser.parse(gson.toJson(dataStatAclNode)).getAsJsonObject(), jsonWriter);
                        }
                    })
            ).collect(Collectors.toList());

    CompletableFuture<Void> allReadsFuture = CompletableFuture.allOf(readFutures.toArray(new CompletableFuture[readFutures.size()]));
    final CompletableFuture<List<Void>> finishedReads = allReadsFuture
            .thenApply(v -> readFutures.stream()
                    .map(CompletableFuture::join)
                    .collect(Collectors.toList()));
    final List<Void> readsDone = finishedReads.get();
    jsonWriter.endArray();
    jsonWriter.close();
    if (LOGGER.isInfoEnabled()) {
        final int readCount = readsDone.size();
        LOGGER.info("{} {} read from {}", readCount, readCount == 1 ? "node" : "nodes", zooKeeperEndpointConfig);
    }
    closeZooKeeper(zooKeeper);
}
 
Example 18
Source File: GsonMessageBodyProvider.java    From immutables with Apache License 2.0 4 votes vote down vote up
void setWriterOptions(JsonWriter writer) {
  writer.setSerializeNulls(serializeNulls);
  writer.setLenient(lenient);
  writer.setHtmlSafe(htmlSafe);
  writer.setIndent(prettyPrinting ? "  " : "");
}
 
Example 19
Source File: JsonWriterFactory.java    From yangtools with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Create a new JsonWriter, which writes to the specified output writer.
 *
 * @param writer Output writer
 * @param indentSize size of the indent
 * @return A JsonWriter instance
 */
public static JsonWriter createJsonWriter(final Writer writer, final int indentSize) {
    JsonWriter jsonWriter = new JsonWriter(writer);
    final String indent = " ".repeat(indentSize);
    jsonWriter.setIndent(indent);
    return jsonWriter;
}