/** * Example to writeJson using StreamingAPI */ private static void writeJson() throws IOException { OutputStream outputStream = new ByteArrayOutputStream(); JsonWriter writer = new JsonWriter(new OutputStreamWriter(outputStream, "UTF-8")); writer.beginObject(); // main object writer.name("message"); writer.value("Hi"); writer.name("place"); // save object Place writer.beginObject(); writer.name("name"); writer.value("World!"); writer.endObject(); writer.endObject(); writer.close(); System.out.println(outputStream.toString()); // print "{"message":"Hi","place":{"name":"World!"}}" } }
private void serializeFileAmount(Gson gson, String recordingPath) { try { JsonWriter writer = new JsonWriter(new FileWriter(recordingPath + FILE_AMOUNT)); gson.toJson(recordAndReplayUtils.getFileAmount(), Integer.class, writer); writer.close(); logger.info("File Amount Serialization completed!"); } catch (Exception e) { logger.error("Error while serializing file amount:", e); } }
private void serializeAttackEventExtraRecorder(Gson gson, String recordingPath) { try { JsonWriter writer = new JsonWriter(new FileWriter(recordingPath + DIRECTION_ORIGIN_LIST)); gson.toJson(directionAndOriginPosRecorderList.getList(), ArrayList.class, writer); writer.close(); directionAndOriginPosRecorderList.reset(); logger.info("AttackEvent extras serialization completed!"); } catch (Exception e) { logger.error("Error while serializing AttackEvent extras:", e); } }
private void serializeCharacterStateEventPositonMap(Gson gson, String recordingPath) { try { JsonWriter writer = new JsonWriter(new FileWriter(recordingPath + STATE_EVENT_POSITION)); gson.toJson(characterStateEventPositionMap.getIdToData(), HashMap.class, writer); writer.close(); characterStateEventPositionMap.reset(); logger.info("CharacterStateEvent positions Serialization completed!"); } catch (Exception e) { logger.error("Error while serializing CharacterStateEvent positions:", e); } }
@Override public String toString() { StringWriter stringWriter = new StringWriter(); try (JsonWriter jsonWriter = new JsonWriter(stringWriter)) { jsonWriter.setIndent("\t"); this.toJson(jsonWriter, false); } catch (IOException ioe) { // Ignored } return stringWriter.toString(); }
private JsonWriter(Writer writer) { this.stream = new com.google.gson.stream.JsonWriter(writer); this.stream.setSerializeNulls(false); this.stream.setLenient(false); this.serializeEmptyStrings = true; }
/** * Reformats the given JSON file. * * @param pathToJson the path to the JSON file to be reformatted * @throws ReportException thrown if the given JSON file is malformed */ private void pretifyJson(String pathToJson) throws ReportException { final String outputPath = pathToJson + ".pretty"; final File in = new File(pathToJson); final File out = new File(outputPath); try (JsonReader reader = new JsonReader(new InputStreamReader(new FileInputStream(in), StandardCharsets.UTF_8)); JsonWriter writer = new JsonWriter(new OutputStreamWriter(new FileOutputStream(out), StandardCharsets.UTF_8))) { prettyPrint(reader, writer); } catch (IOException ex) { LOGGER.debug("Malformed JSON?", ex); throw new ReportException("Unable to generate json report", ex); } if (out.isFile() && in.isFile() && in.delete()) { try { org.apache.commons.io.FileUtils.moveFile(out, in); } catch (IOException ex) { LOGGER.error("Unable to generate pretty report, caused by: ", ex.getMessage()); } } }
@RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public void exportData(HttpServletResponse resp, Principal prin) throws IOException { resp.setContentType(MediaType.APPLICATION_JSON_VALUE); // this writer puts things out onto the wire JsonWriter writer = new JsonWriter(resp.getWriter()); writer.setIndent(" "); try { writer.beginObject(); writer.name("exported-at"); writer.value(dateFormat.format(new Date())); writer.name("exported-from"); writer.value(config.getIssuer()); writer.name("exported-by"); writer.value(prin.getName()); // delegate to the service to do the actual export exporter.exportData(writer); writer.endObject(); // end root writer.close(); } catch (IOException e) { logger.error("Unable to export data", e); } }
JsonWriter writer = new JsonWriter( new OutputStreamWriter(buffer, StandardCharsets.UTF_8)); try {
/** * Convert all past {@link JobState}s of the given job. * * @param jobName job name * @param writer {@link java.io.Writer} to write the json document * @throws IOException */ public void convertAll(String jobName, Writer writer) throws IOException { List<? extends JobState> jobStates = this.jobStateStore.getAll(jobName); if (jobStates.isEmpty()) { LOGGER.warn(String.format("No job state found for job with name %s", jobName)); return; } try (JsonWriter jsonWriter = new JsonWriter(writer)) { jsonWriter.setIndent("\t"); writeJobStates(jsonWriter, jobStates); } }
void serializeRecordedEvents(List<RecordedEvent> events, String filePath) { try { JsonWriter writer = new JsonWriter(new FileWriter(filePath)); writer.beginObject(); writer.name("events"); writer.beginArray(); for (RecordedEvent event : events) { writer.beginObject(); writer.name("entityRef_ID").value(event.getEntityId()); writer.name("timestamp").value(event.getTimestamp()); writer.name("index").value(event.getIndex()); writer.name("event_class").value(event.getEvent().getClass().getName()); writer.name("event_data"); writer.beginObject(); writeSpecificEventData(writer, event.getEvent()); writer.endObject(); writer.endObject(); } writer.endArray(); writer.endObject(); writer.close(); } catch (Exception e) { logger.error("Error while serializing events:", e); } }
/** * Convert a single {@link JobState} of the given job instance. * * @param jobName job name * @param jobId job ID * @param writer {@link java.io.Writer} to write the json document * @throws IOException */ public void convert(String jobName, String jobId, Writer writer) throws IOException { List<? extends JobState> jobStates = this.jobStateStore.getAll(jobName, jobId + JOB_STATE_STORE_TABLE_SUFFIX); if (jobStates.isEmpty()) { LOGGER.warn(String.format("No job state found for job with name %s and id %s", jobName, jobId)); return; } try (JsonWriter jsonWriter = new JsonWriter(writer)) { jsonWriter.setIndent("\t"); // There should be only a single job state writeJobState(jsonWriter, jobStates.get(0)); } }
/** * Start the generation of meta file. * * @throws IOException if unable to write to meta file (permissions, disk full etc) */ public DataStep startMetaFileGeneration(Instant snapshotInstant) throws IOException { // Compute meta file name. this.snapshotInstant = snapshotInstant; String fileName = MetaFileInfo.getMetaFileName(snapshotInstant); metaFilePath = Paths.get(metaProxy.getLocalMetaFileDirectory().toString(), fileName); Path tempMetaFilePath = Paths.get(metaProxy.getLocalMetaFileDirectory().toString(), fileName + ".tmp"); logger.info("Starting to write a new meta file: {}", metaFilePath); jsonWriter = new JsonWriter(new FileWriter(tempMetaFilePath.toFile())); jsonWriter.beginObject(); jsonWriter.name(MetaFileInfo.META_FILE_INFO); jsonWriter.jsonValue(metaFileInfo.toString()); jsonWriter.name(MetaFileInfo.META_FILE_DATA); jsonWriter.beginArray(); return this; }
@SuppressWarnings("unchecked") @Override public void write(Gson gson, Type type, Object object, OutputStream stream) throws IOException { @Nullable JsonWriter writer = null; boolean wasOriginalException = false; try { writer = new JsonWriter(new BufferedWriter(new OutputStreamWriter(stream, CHARSET_NAME))); options.setWriterOptions(writer); gson.getAdapter((TypeToken<Object>) TypeToken.get(type)).write(writer, object); } catch (IOException ex) { wasOriginalException = true; throw ex; } catch (Exception ex) { wasOriginalException = true; throw new IOException(ex); } finally { if (writer != null) { try { // underlying stream should not be closed, just flushing writer.flush(); } catch (IOException ex) { if (!wasOriginalException) { throw ex; } } } } }
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();
JsonWriter writer = new JsonWriter(new OutputStreamWriter(outStream)))
try { StringBuilderWriter out = new StringBuilderWriter(1024); JsonWriter writer = new JsonWriter(out);
@Test public void propagateGsonAttributes() { Gson gson = new GsonBuilder() .serializeNulls() .disableHtmlEscaping() .setPrettyPrinting() .create(); GsonOptions options = new GsonOptions(gson, true); JsonReader reader = new JsonReader(new StringReader("")); options.setReaderOptions(reader); check(reader.isLenient()); JsonWriter writer = new JsonWriter(new StringWriter()); options.setWriterOptions(writer); check(writer.isLenient()); check(!writer.isHtmlSafe()); check(writer.getSerializeNulls()); // checks pretty printing check(gson.toJson(Collections.singletonMap("k", "v"))).is("{\n \"k\": \"v\"\n}"); } }
public JsonCreatorCanonical(OutputStreamWriter osw) { stack = new Stack<JsonCreatorCanonical.JsonCanObject>(); gson = new JsonWriter(osw); name = null; }
try ( final OutputStreamWriter osw = new OutputStreamWriter(out); final JsonWriter writer = new JsonWriter(osw) ) { addFacetsFromSolrResponseToJsonWriter(response, writer); try ( final OutputStreamWriter osw = new OutputStreamWriter(out); final JsonWriter writer = new JsonWriter(osw) ) { addStatsFromSolrResponseToJsonWriter(response, writer);