Java Code Examples for com.fasterxml.jackson.databind.ObjectWriter#writeValue()
The following examples show how to use
com.fasterxml.jackson.databind.ObjectWriter#writeValue() .
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: AbstractJackson2View.java From spring-analysis-note with MIT License | 6 votes |
/** * Write the actual JSON content to the stream. * @param stream the output stream to use * @param object the value to be rendered, as returned from {@link #filterModel} * @throws IOException if writing failed */ protected void writeContent(OutputStream stream, Object object) throws IOException { JsonGenerator generator = this.objectMapper.getFactory().createGenerator(stream, this.encoding); writePrefix(generator, object); Object value = object; Class<?> serializationView = null; FilterProvider filters = null; if (value instanceof MappingJacksonValue) { MappingJacksonValue container = (MappingJacksonValue) value; value = container.getValue(); serializationView = container.getSerializationView(); filters = container.getFilters(); } ObjectWriter objectWriter = (serializationView != null ? this.objectMapper.writerWithView(serializationView) : this.objectMapper.writer()); if (filters != null) { objectWriter = objectWriter.with(filters); } objectWriter.writeValue(generator, value); writeSuffix(generator, object); generator.flush(); }
Example 2
Source File: MappingJackson2MessageConverter.java From spring-analysis-note with MIT License | 6 votes |
/** * Map the given object to a {@link BytesMessage}. * @param object the object to be mapped * @param session current JMS session * @param objectWriter the writer to use * @return the resulting message * @throws JMSException if thrown by JMS methods * @throws IOException in case of I/O errors * @since 4.3 * @see Session#createBytesMessage */ protected BytesMessage mapToBytesMessage(Object object, Session session, ObjectWriter objectWriter) throws JMSException, IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(1024); if (this.encoding != null) { OutputStreamWriter writer = new OutputStreamWriter(bos, this.encoding); objectWriter.writeValue(writer, object); } else { // Jackson usually defaults to UTF-8 but can also go straight to bytes, e.g. for Smile. // We use a direct byte array argument for the latter case to work as well. objectWriter.writeValue(bos, object); } BytesMessage message = session.createBytesMessage(); message.writeBytes(bos.toByteArray()); if (this.encodingPropertyName != null) { message.setStringProperty(this.encodingPropertyName, (this.encoding != null ? this.encoding : DEFAULT_ENCODING)); } return message; }
Example 3
Source File: UtilitiesTestBase.java From hudi with Apache License 2.0 | 6 votes |
/** * Converts the json records into CSV format and writes to a file. * * @param hasHeader whether the CSV file should have a header line. * @param sep the column separator to use. * @param lines the records in JSON format. * @param fs {@link FileSystem} instance. * @param targetPath File path. * @throws IOException */ public static void saveCsvToDFS( boolean hasHeader, char sep, String[] lines, FileSystem fs, String targetPath) throws IOException { Builder csvSchemaBuilder = CsvSchema.builder(); ArrayNode arrayNode = mapper.createArrayNode(); Arrays.stream(lines).forEachOrdered( line -> { try { arrayNode.add(mapper.readValue(line, ObjectNode.class)); } catch (IOException e) { throw new HoodieIOException( "Error converting json records into CSV format: " + e.getMessage()); } }); arrayNode.get(0).fieldNames().forEachRemaining(csvSchemaBuilder::addColumn); ObjectWriter csvObjWriter = new CsvMapper() .writerFor(JsonNode.class) .with(csvSchemaBuilder.setUseHeader(hasHeader).setColumnSeparator(sep).build()); PrintStream os = new PrintStream(fs.create(new Path(targetPath), true)); csvObjWriter.writeValue(os, arrayNode); os.flush(); os.close(); }
Example 4
Source File: JsonMerger.java From carnotzet with Apache License 2.0 | 6 votes |
/** * Properties of file2 have precedence over the ones in file1 */ @Override public void merge(Path file1Path, Path file2Path, Path output) { ObjectMapper mapper = new ObjectMapper(); ObjectWriter writer = mapper.writer(new DefaultPrettyPrinter()); try (InputStream in1 = Files.newInputStream(file1Path)) { try (InputStream in2 = Files.newInputStream(file2Path)) { JsonNode file1 = mapper.readTree(in1); JsonNode file2 = mapper.readTree(in2); JsonNode merged = merge(file1, file2); writer.writeValue(output.toFile(), merged); } } catch (IOException e) { throw new UncheckedIOException(e); } }
Example 5
Source File: PropertyFilteringMessageBodyWriter.java From jackson-jaxrs-propertyfiltering with Apache License 2.0 | 6 votes |
private void writeValue(ObjectWriter writer, PropertyFilter filter, Object value, OutputStream outputStream) throws IOException { JsonGenerator generator = writer.getFactory().createGenerator(outputStream); // Important: we are NOT to close the underlying stream after // mapping, so we need to instruct generator generator.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET); generator = new PropertyFilteringJsonGenerator(generator, filter); boolean ok = false; try { writer.writeValue(generator, value); ok = true; } finally { if (ok) { generator.close(); } else { try { generator.close(); } catch (Exception ignored) {} } } }
Example 6
Source File: JacksonSerializationProvider.java From servicetalk with Apache License 2.0 | 5 votes |
private static void serialize0(final ObjectWriter writer, final Object toSerialize, final Buffer destination) { try { writer.writeValue(asOutputStream(destination), toSerialize); } catch (IOException e) { throwException(e); } }
Example 7
Source File: DynamicSimulationResultSerializer.java From powsybl-core with Mozilla Public License 2.0 | 5 votes |
public static void write(DynamicSimulationResult result, Path jsonFile) { Objects.requireNonNull(result); Objects.requireNonNull(jsonFile); try (OutputStream os = Files.newOutputStream(jsonFile)) { ObjectMapper objectMapper = JsonUtil.createObjectMapper(); SimpleModule module = new SimpleModule(); module.addSerializer(DynamicSimulationResult.class, new DynamicSimulationResultSerializer()); objectMapper.registerModule(module); ObjectWriter writer = objectMapper.writerWithDefaultPrettyPrinter(); writer.writeValue(os, result); } catch (IOException e) { throw new UncheckedIOException(e); } }
Example 8
Source File: GenWorlds.java From vethrfolnir-mu with GNU General Public License v3.0 | 5 votes |
public static void main(String[] args) throws Exception { NodeList data = getDocument(GenWorlds.class.getResourceAsStream("/worlds.xml")); ArrayList<Region> regions = parseData(data); ObjectWriter writer = GenData.getWriter(); writer.writeValue(new FileOutputStream("./dist/GameServer/system/static/world-data.json"), regions); System.out.println("Regions: "+regions); }
Example 9
Source File: JsonLoadFlowParameters.java From powsybl-core with Mozilla Public License 2.0 | 5 votes |
/** * Writes parameters as JSON to an output stream. */ public static void write(LoadFlowParameters parameters, OutputStream outputStream) { try { ObjectMapper objectMapper = createObjectMapper(); ObjectWriter writer = objectMapper.writerWithDefaultPrettyPrinter(); writer.writeValue(outputStream, parameters); } catch (IOException e) { throw new UncheckedIOException(e); } }
Example 10
Source File: PentahoAvroOutputFormat.java From pentaho-hadoop-shims with Apache License 2.0 | 5 votes |
protected void writeAvroSchemaToFile( String schemaFilename ) throws KettleFileException, IOException { ObjectNode schemaObjectNode = this.getSchemaObjectNode(); if ( schemaObjectNode != null && schemaFilename != null ) { ObjectMapper mapper = new ObjectMapper(); ObjectWriter writer = mapper.writer( new DefaultPrettyPrinter() ); writer.writeValue( KettleVFS.getOutputStream( schemaFilename, variableSpace, false ), schemaObjectNode ); } }
Example 11
Source File: JsonDynamicSimulationParameters.java From powsybl-core with Mozilla Public License 2.0 | 5 votes |
/** * Writes parameters as JSON to an output stream. */ public static void write(DynamicSimulationParameters parameters, OutputStream outputStream) { try { ObjectMapper objectMapper = createObjectMapper(); ObjectWriter writer = objectMapper.writerWithDefaultPrettyPrinter(); writer.writeValue(outputStream, parameters); } catch (IOException e) { throw new UncheckedIOException(e); } }
Example 12
Source File: ZeroCodeReportGeneratorImpl.java From zerocode with Apache License 2.0 | 5 votes |
public void generateCsvReport(List<ZeroCodeCsvReport> zeroCodeCsvReportRows) { /* * Write to a CSV file */ CsvSchema schema = CsvSchema.builder() .setUseHeader(true) .addColumn("scenarioName") .addColumn("scenarioLoop", CsvSchema.ColumnType.NUMBER) .addColumn("stepName") .addColumn("stepLoop", CsvSchema.ColumnType.NUMBER) .addColumn("correlationId") .addColumn("requestTimeStamp") .addColumn("responseDelayMilliSec", CsvSchema.ColumnType.NUMBER) .addColumn("responseTimeStamp") .addColumn("result") .addColumn("method") .build(); CsvMapper csvMapper = new CsvMapper(); csvMapper.enable(CsvParser.Feature.WRAP_AS_ARRAY); ObjectWriter writer = csvMapper.writer(schema.withLineSeparator("\n")); try { writer.writeValue( new File(TARGET_FULL_REPORT_DIR + TARGET_FULL_REPORT_CSV_FILE_NAME //"_" + //LocalDateTime.now().toString().replace(":", "-") + //".csv" ), zeroCodeCsvReportRows); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("Exception while Writing full CSV report. Details: " + e); } }
Example 13
Source File: JsonSensitivityComputationParameters.java From powsybl-core with Mozilla Public License 2.0 | 5 votes |
/** * Writes parameters as JSON to an output stream. */ public static void write(SensitivityComputationParameters parameters, OutputStream outputStream) { Objects.requireNonNull(parameters); Objects.requireNonNull(outputStream); try { ObjectMapper objectMapper = createObjectMapper(); ObjectWriter writer = objectMapper.writerWithDefaultPrettyPrinter(); writer.writeValue(outputStream, parameters); } catch (IOException e) { throw new UncheckedIOException(e); } }
Example 14
Source File: SensitivityComputationResultJsonSerializer.java From powsybl-core with Mozilla Public License 2.0 | 5 votes |
/** * Write sensitivity computation results in JSON format to writer * @param result The sensitivity computation results to export * @param writer The writer to write to * @throws IOException */ public static void write(SensitivityComputationResults result, Writer writer) throws IOException { Objects.requireNonNull(result); Objects.requireNonNull(writer); ObjectWriter objectWriter = JsonUtil.createObjectMapper().writerWithDefaultPrettyPrinter(); objectWriter.writeValue(writer, result); }
Example 15
Source File: PackageTask.java From azure-gradle-plugins with MIT License | 4 votes |
private void writeObjectToFile(final ObjectWriter objectWriter, final Object object, final File targetFile) throws IOException { targetFile.getParentFile().mkdirs(); targetFile.createNewFile(); objectWriter.writeValue(targetFile, object); }
Example 16
Source File: ClientsManager.java From V8LogScanner with MIT License | 4 votes |
public void saveProfile() throws IOException { ObjectMapper mapper = new ObjectMapper(); ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter(); ow.writeValue(new File(profileFileName), localClient().getProfile()); }
Example 17
Source File: DefaultCsvEventService.java From dhis2-core with BSD 3-Clause "New" or "Revised" License | 4 votes |
@Override public void writeEvents( OutputStream outputStream, Events events, boolean withHeader ) throws IOException { ObjectWriter writer = CSV_MAPPER.writer( CSV_SCHEMA.withUseHeader( withHeader ) ); List<CsvEventDataValue> dataValues = new ArrayList<>(); for ( Event event : events.getEvents() ) { CsvEventDataValue templateDataValue = new CsvEventDataValue(); templateDataValue.setEvent( event.getEvent() ); templateDataValue.setStatus( event.getStatus() != null ? event.getStatus().name() : null ); templateDataValue.setProgram( event.getProgram() ); templateDataValue.setProgramStage( event.getProgramStage() ); templateDataValue.setEnrollment( event.getEnrollment() ); templateDataValue.setOrgUnit( event.getOrgUnit() ); templateDataValue.setEventDate( event.getEventDate() ); templateDataValue.setDueDate( event.getDueDate() ); templateDataValue.setStoredBy( event.getStoredBy() ); templateDataValue.setCompletedDate( event.getCompletedDate() ); templateDataValue.setCompletedBy( event.getCompletedBy() ); if ( event.getGeometry() != null ) { templateDataValue.setGeometry( event.getGeometry().toText() ); if ( event.getGeometry().getGeometryType().equals( "Point" ) ) { templateDataValue.setLongitude( event.getGeometry().getCoordinate().x ); templateDataValue.setLatitude( event.getGeometry().getCoordinate().y ); } } for ( DataValue value : event.getDataValues() ) { CsvEventDataValue dataValue = new CsvEventDataValue( templateDataValue ); dataValue.setDataElement( value.getDataElement() ); dataValue.setValue( value.getValue() ); dataValue.setProvidedElsewhere( value.getProvidedElsewhere() ); if ( value.getStoredBy() != null ) { dataValue.setStoredBy( value.getStoredBy() ); } dataValues.add( dataValue ); } } writer.writeValue( outputStream, dataValues ); }
Example 18
Source File: WidgetRepositoryTest.java From bonita-ui-designer with GNU General Public License v2.0 | 4 votes |
private void writeWidgetMetadataInFile(Widget widget, Path path) throws IOException { ObjectWriter writer = new ObjectMapper().writer(); writer.writeValue(path.toFile(), widget); }
Example 19
Source File: ExportMetadata.java From Knowage-Server with GNU Affero General Public License v3.0 | 4 votes |
public static void writeToJsonFile(final ExportMetadata instance, final Path metadata) throws IOException { ObjectMapper mapper = new ObjectMapper(); ObjectWriter writer = mapper.writer(new DefaultPrettyPrinter()); writer.writeValue(metadata.toFile(), instance); }
Example 20
Source File: MappingJackson2MessageConverter.java From spring-analysis-note with MIT License | 3 votes |
/** * Map the given object to a {@link TextMessage}. * @param object the object to be mapped * @param session current JMS session * @param objectWriter the writer to use * @return the resulting message * @throws JMSException if thrown by JMS methods * @throws IOException in case of I/O errors * @since 4.3 * @see Session#createBytesMessage */ protected TextMessage mapToTextMessage(Object object, Session session, ObjectWriter objectWriter) throws JMSException, IOException { StringWriter writer = new StringWriter(); objectWriter.writeValue(writer, object); return session.createTextMessage(writer.toString()); }