Java Code Examples for com.fasterxml.jackson.databind.ObjectWriter

The following examples show how to use com.fasterxml.jackson.databind.ObjectWriter. These examples are extracted from open source projects. 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: hudi   Author: apache   File: UtilitiesTestBase.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 #2
Source Project: cyberduck   Author: iterate-ch   File: TripleCryptOutputStream.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void close() throws IOException {
    try {
        final EncryptedDataContainer encrypted = cipher.doFinal();
        super.write(encrypted.getContent());
        final String tag = CryptoUtils.byteArrayToString(encrypted.getTag());
        final ObjectReader reader = session.getClient().getJSON().getContext(null).readerFor(FileKey.class);
        final FileKey fileKey = reader.readValue(status.getFilekey().array());
        fileKey.setTag(tag);
        final ObjectWriter writer = session.getClient().getJSON().getContext(null).writerFor(FileKey.class);
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        writer.writeValue(out, fileKey);
        status.setFilekey(ByteBuffer.wrap(out.toByteArray()));
    }
    catch(CryptoSystemException e) {
        throw new IOException(e);
    }
    finally {
        super.close();
    }
}
 
Example #3
Source Project: syndesis   Author: syndesisio   File: SqlMetadataAdapterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void adaptForSqlBatchUpdateTest() throws IOException {
    CamelContext camelContext = new DefaultCamelContext();
    SqlConnectorMetaDataExtension ext = new SqlConnectorMetaDataExtension(camelContext);
    Map<String,Object> parameters = new HashMap<>();
    for (final String name: PROPS.stringPropertyNames()) {
        parameters.put(name.substring(name.indexOf('.') + 1), PROPS.getProperty(name));
    }
    parameters.put("query", "INSERT INTO NAME (FIRSTNAME, LASTNAME) VALUES (:#firstname, :#lastname)");
    parameters.put("batch", true);
    Optional<MetaData> metadata = ext.meta(parameters);
    SqlMetadataRetrieval adapter = new SqlMetadataRetrieval();

    SyndesisMetadata syndesisMetaData2 = adapter.adapt(camelContext, "sql", "sql-connector", parameters, metadata.get());
    String expectedMetadata = IOUtils.toString(this.getClass().getResource("/sql/name_sql_batch_update_metadata.json"), StandardCharsets.UTF_8).trim();
    ObjectWriter writer = JsonUtils.writer();
    String actualMetadata = writer.with(writer.getConfig().getDefaultPrettyPrinter()).writeValueAsString(syndesisMetaData2);
    assertThatJson(actualMetadata).isEqualTo(expectedMetadata);
}
 
Example #4
@Override
public void writeTo(Object o, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
                    MultivaluedMap<String, Object> httpHeaders, OutputStream os) throws IOException {
  PropertyFiltering annotation = findPropertyFiltering(annotations);
  PropertyFilter propertyFilter = PropertyFilterBuilder.newBuilder(uriInfo).forAnnotation(annotation);

  if (!propertyFilter.hasFilters()) {
    write(o, type, genericType, annotations, mediaType, httpHeaders, os);
    return;
  }

  Timer timer = getTimer();
  Timer.Context context = timer.time();

  try {
    ObjectMapper mapper = getJsonProvider().locateMapper(type, mediaType);
    ObjectWriter writer = JsonEndpointConfig.forWriting(mapper.writer(), annotations, null).getWriter();
    writeValue(writer, propertyFilter, o, os);
  } finally {
    context.stop();
  }
}
 
Example #5
Source Project: dremio-oss   Author: dremio   File: ElasticBaseTestQuery.java    License: Apache License 2.0 6 votes vote down vote up
public static void compareJson(String expected, String actual) throws IOException {
  if(ElasticsearchCluster.USE_EXTERNAL_ES5){
    // ignore json comparison for now
    return;
  }

  ObjectMapper m = new ObjectMapper();
  JsonNode expectedRootNode = m.readTree(expected);
  JsonNode actualRootNode = m.readTree(actual);
  if (!expectedRootNode.equals(actualRootNode)) {
    ObjectWriter writer = m.writerWithDefaultPrettyPrinter();
    String message = String.format("Comparison between JSON values failed.\nExpected:\n%s\nActual:\n%s", expected, actual);
    // assertEquals gives a better diff
    assertEquals(message, writer.writeValueAsString(expectedRootNode), writer.writeValueAsString(actualRootNode));
    throw new RuntimeException(message);
  }
}
 
Example #6
Source Project: syndesis   Author: syndesisio   File: SqlMetadataAdapterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void adaptForSqlUpdateNoParamTest() throws IOException {
    CamelContext camelContext = new DefaultCamelContext();
    SqlConnectorMetaDataExtension ext = new SqlConnectorMetaDataExtension(camelContext);
    Map<String,Object> parameters = new HashMap<>();
    for (final String name: PROPS.stringPropertyNames()) {
        parameters.put(name.substring(name.indexOf('.') + 1), PROPS.getProperty(name));
    }
    parameters.put("query", "INSERT INTO NAME (FIRSTNAME, LASTNAME) VALUES ('Sheldon', 'Cooper')");
    Optional<MetaData> metadata = ext.meta(parameters);
    SqlMetadataRetrieval adapter = new SqlMetadataRetrieval();

    SyndesisMetadata syndesisMetaData2 = adapter.adapt(camelContext, "sql", "sql-connector", parameters, metadata.get());
    String expectedMetadata = IOUtils.toString(this.getClass().getResource("/sql/name_sql_update_no_param_metadata.json"), StandardCharsets.UTF_8).trim();
    ObjectWriter writer = JsonUtils.writer();
    String actualMetadata = writer.with(writer.getConfig().getDefaultPrettyPrinter()).writeValueAsString(syndesisMetaData2);
    assertThatJson(actualMetadata).isEqualTo(expectedMetadata);
}
 
Example #7
Source Project: floodlight_with_topoguard   Author: xuraylei   File: SyncClient.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean execute(String[] tokens, String line) throws Exception {
    if (tokens.length < 2) {
        err.println("Usage: " + syntaxString());
        return false;
    }
    if (!checkStoreSettings()) return false;

    StringReader sr = new StringReader(line);
    while (sr.read() != ' ');
    JsonParser jp = mjf.createJsonParser(sr);
             
    JsonNode keyNode = validateJson(jp);
    if (keyNode == null) return false;
    
    ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter();
    out.println("Deleting Key:");
    out.println(writer.writeValueAsString(keyNode));
    out.println("");
    
    storeClient.delete(keyNode);
    out.println("Success");

    return false;
}
 
Example #8
Source Project: amazon-neptune-tools   Author: awslabs   File: NeptuneExportService.java    License: Apache License 2.0 6 votes vote down vote up
private void uploadCompletionFileToS3(TransferManager transferManager, File directory, S3ObjectInfo outputS3ObjectInfo) throws IOException {
    if (!completionFileS3Path.isEmpty()) {

        File completionFile = new File(TEMP_PATH, directory.getName() + ".json");

        ObjectNode neptuneExportNode = JsonNodeFactory.instance.objectNode();
        neptuneExportNode.put("output", outputS3ObjectInfo.toString());
        completionFilePayload.set("neptuneExport", neptuneExportNode);

        try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(completionFile), UTF_8))) {
            ObjectWriter objectWriter = new ObjectMapper().writer().withDefaultPrettyPrinter();
            writer.write(objectWriter.writeValueAsString(completionFilePayload));
        }

        S3ObjectInfo completionFileS3ObjectInfo = new S3ObjectInfo(completionFileS3Path).withNewKeySuffix(completionFile.getName());

        Upload upload = transferManager.upload(completionFileS3ObjectInfo.bucket(), completionFileS3ObjectInfo.key(), completionFile);
        try {
            upload.waitForUploadResult();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            logger.log(e.getMessage());
        }
    }
}
 
Example #9
Source Project: quarkus   Author: quarkusio   File: FunqyLambdaBindingRecorder.java    License: Apache License 2.0 6 votes vote down vote up
public void chooseInvoker(FunqyConfig config) {
    // this is done at Runtime so that we can change it with an environment variable.
    if (config.export.isPresent()) {
        invoker = FunctionRecorder.registry.matchInvoker(config.export.get());
        if (invoker == null) {
            throw new RuntimeException("quarkus.funqy.export does not match a function: " + config.export.get());
        }
    } else if (FunctionRecorder.registry.invokers().size() == 0) {
        throw new RuntimeException("There are no functions to process lambda");

    } else if (FunctionRecorder.registry.invokers().size() > 1) {
        throw new RuntimeException("Too many functions.  You need to set quarkus.funqy.export");
    } else {
        invoker = FunctionRecorder.registry.invokers().iterator().next();
    }
    if (invoker.hasInput()) {
        reader = (ObjectReader) invoker.getBindingContext().get(ObjectReader.class.getName());
    }
    if (invoker.hasOutput()) {
        writer = (ObjectWriter) invoker.getBindingContext().get(ObjectWriter.class.getName());
    }

}
 
Example #10
Source Project: ontopia   Author: ontopia   File: JacksonRepresentationImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected ObjectWriter createObjectWriter() {
	ObjectWriter writer = super.createObjectWriter();

	for (SerializationFeature feature : SerializationFeature.values()) {
		boolean hasDefault = DEFAULT_SERIALIZATION_FEATURES.contains(feature);
		Parameter parameter = ContextUtils.getParameter(ContextUtils.getCurrentApplicationContext(), SERIALIZATION_FEATURE + feature.name());
		if ((parameter != null) || hasDefault) {
			if (ContextUtils.getParameterAsBoolean(parameter, feature.enabledByDefault() || hasDefault)) {
				writer = writer.with(feature);
			} else {
				writer = writer.without(feature);
			}
		}
	}
	return writer;
}
 
Example #11
Source Project: angular-rest-springsecurity   Author: philipsorst   File: BlogPostResource.java    License: Apache License 2.0 6 votes vote down vote up
@GET
@Produces(MediaType.APPLICATION_JSON)
public String list() throws IOException
{
    this.logger.info("list()");

    ObjectWriter viewWriter;
    if (this.isAdmin()) {
        viewWriter = this.mapper.writerWithView(JsonViews.Admin.class);
    } else {
        viewWriter = this.mapper.writerWithView(JsonViews.User.class);
    }
    List<BlogPost> allEntries = this.blogPostDao.findAll();

    return viewWriter.writeValueAsString(allEntries);
}
 
Example #12
Source Project: pinpoint   Author: naver   File: ObjectReaderIT.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testWriteValue() throws Exception {
    __POJO pojo = new __POJO();
    pojo.setName("Jackson");
    
    ObjectWriter writer = mapper.writer();

    String jsonStr = writer.writeValueAsString(pojo);
    byte[] jsonByte = writer.writeValueAsBytes(pojo);

    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    verifier.printCache();

    Method writeval1 = ObjectWriter.class.getMethod("writeValueAsString", Object.class);
    Method writeval2 = ObjectWriter.class.getMethod("writeValueAsBytes", Object.class);

    verifier.verifyTrace(event("JACKSON", writeval1, annotation("jackson.json.length", jsonStr.length())));
    verifier.verifyTrace(event("JACKSON", writeval2, annotation("jackson.json.length", jsonByte.length)));

    verifier.verifyTraceCount(0);
}
 
Example #13
Source Project: vavr-jackson   Author: vavr-io   File: SetTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void test1() throws IOException {
    ObjectWriter writer = mapper().writer();
    Set<?> src = of(1, 2, 5);
    String json = writer.writeValueAsString(src);
    Assertions.assertEquals(genJsonList(1, 2, 5), json);
    Set<?> dst = mapper().readValue(json, typeReference());
    Assertions.assertEquals(src, dst);
}
 
Example #14
Source Project: sakai   Author: sakaiproject   File: JacksonUtil.java    License: Educational Community License v2.0 5 votes vote down vote up
public static String prettyPrint(Object obj)
		throws com.fasterxml.jackson.core.JsonProcessingException {
	ObjectMapper mapper = new ObjectMapper();

	// ***IMPORTANT!!!*** for Jackson 2.x use the line below instead of the one above: 
	// ObjectWriter writer = mapper.writer().withDefaultPrettyPrinter();
	// return mapper.writeValueAsString(obj);
	ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter();
	return writer.writeValueAsString(obj);
}
 
Example #15
Source Project: powsybl-core   Author: powsybl   File: SecurityAnalysisResultSerializer.java    License: Mozilla Public License 2.0 5 votes vote down vote up
public static void write(SecurityAnalysisResult result, Writer writer) throws IOException {
    Objects.requireNonNull(result);
    Objects.requireNonNull(writer);

    ObjectMapper objectMapper = JsonUtil.createObjectMapper()
            .registerModule(new SecurityAnalysisJsonModule());

    ObjectWriter objectWriter = objectMapper.writerWithDefaultPrettyPrinter();
    objectWriter.writeValue(writer, result);
}
 
Example #16
Source Project: tutorials   Author: eugenp   File: AdvancedAnnotationsUnitTest.java    License: MIT License 5 votes vote down vote up
@Test
public void whenNotUsingJsonAppendAnnotation_thenCorrect() throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();

    BeanWithoutAppend bean = new BeanWithoutAppend(2, "Bean Without Append Annotation");
    ObjectWriter writer = mapper.writerFor(BeanWithoutAppend.class)
        .withAttribute("version", "1.0");
    String jsonString = writer.writeValueAsString(bean);

    assertThat(jsonString, not(containsString("version")));
    assertThat(jsonString, not(containsString("1.0")));
}
 
Example #17
Source Project: Bats   Author: lealone   File: PhysicalPlan.java    License: Apache License 2.0 5 votes vote down vote up
/** Converts a physical plan to a string. (Opposite of {@link #parse}.) */
public String unparse(ObjectWriter writer) {
  try {
    return writer.writeValueAsString(this);
  } catch (JsonProcessingException e) {
    throw new RuntimeException(e);
  }
}
 
Example #18
Source Project: spring-analysis-note   Author: Vip-Augus   File: Jackson2JsonEncoder.java    License: MIT License 5 votes vote down vote up
@Override
protected ObjectWriter customizeWriter(ObjectWriter writer, @Nullable MimeType mimeType,
		ResolvableType elementType, @Nullable Map<String, Object> hints) {

	return (this.ssePrettyPrinter != null &&
			MediaType.TEXT_EVENT_STREAM.isCompatibleWith(mimeType) &&
			writer.getConfig().isEnabled(SerializationFeature.INDENT_OUTPUT) ?
			writer.with(this.ssePrettyPrinter) : writer);
}
 
Example #19
Source Project: onos   Author: opennetworkinglab   File: CodecTools.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns a JSON format string from a Jackson object node.
 *
 * @param node JSON object node
 * @return string with JSON format
 */
public static String jsonToString(ObjectNode node) {
    ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
    String jsonString = null;
    try {
        jsonString = ow.writeValueAsString(node);
    } catch (JsonProcessingException e) {
        log.error("Parse json to string failed {}", e.getMessage());
    }

    return jsonString;
}
 
Example #20
Source Project: cyberduck   Author: iterate-ch   File: SDSNodeIdProvider.java    License: GNU General Public License v3.0 5 votes vote down vote up
public void setFileKey(final TransferStatus status) throws BackgroundException {
    final FileKey fileKey = TripleCryptConverter.toSwaggerFileKey(Crypto.generateFileKey());
    final ObjectWriter writer = session.getClient().getJSON().getContext(null).writerFor(FileKey.class);
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        writer.writeValue(out, fileKey);
    }
    catch(IOException e) {
        throw new DefaultIOExceptionMappingService().map(e);
    }
    status.setFilekey(ByteBuffer.wrap(out.toByteArray()));
    status.setEncryption(new Encryption.Algorithm("AES256", null));
}
 
Example #21
Source Project: jpmml-model   Author: jpmml   File: JacksonUtil.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
static
public void write(PMMLObject object, OutputStream os) throws IOException {
	ObjectMapper objectMapper = createObjectMapper(null);

	ObjectWriter objectWriter = objectMapper.writerWithDefaultPrettyPrinter();

	objectWriter.writeValue(os, object);
}
 
Example #22
Source Project: singleton   Author: vmware   File: JSONUtils.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Write a Map<String, Object> to a json file.
 * 
 * @param filePath
 * @param map
 */
public static void writeMapToJsonFile(String filePath, Map<String, Object> map) {
	
	try (FileWriter writer = new FileWriter(filePath)){
		
		ObjectWriter bw = new ObjectMapper().writerWithDefaultPrettyPrinter();
		writer.write(bw.writeValueAsString(map));
	} catch (IOException e) {
		logger.error(e.getMessage(), e);
	} 
}
 
Example #23
Source Project: jackson-datatype-money   Author: zalando   File: MonetaryAmountSerializerTest.java    License: MIT License 5 votes vote down vote up
@ParameterizedTest
@MethodSource("amounts")
void shouldSerializeWithFormattedGermanValue(final MonetaryAmount amount) throws JsonProcessingException {
    final ObjectMapper unit = unit(new MoneyModule().withDefaultFormatting());

    final String expected = "{\"amount\":29.95,\"currency\":\"EUR\",\"formatted\":\"29,95 EUR\"}";

    final ObjectWriter writer = unit.writer().with(Locale.GERMANY);
    final String actual = writer.writeValueAsString(amount);

    assertThat(actual, is(expected));
}
 
Example #24
Source Project: log4j2-elasticsearch   Author: rfoltyns   File: BufferedBulkTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void canSerializeUniqueItemsSeparately() throws IOException {

    // given
    ObjectWriter writer = spy(new ObjectMapper().writerFor(BufferedIndex.class));

    CompositeByteBuf byteBuf1 = createDefaultTestByteBuf();
    ItemSource<ByteBuf> source1 = new ByteBufItemSource(byteBuf1, source -> {});
    String index1 = UUID.randomUUID().toString();
    BulkableAction action1 = new BufferedIndex.Builder(source1)
            .index(index1)
            .build();

    CompositeByteBuf byteBuf2 = createDefaultTestByteBuf();
    ItemSource<ByteBuf> source2 = new ByteBufItemSource(byteBuf2, source -> {});
    String index2 = UUID.randomUUID().toString();
    BulkableAction action2 = new BufferedIndex.Builder(source2)
            .index(index2)
            .build();

    BufferedBulk bulk = (BufferedBulk) new BufferedBulk.Builder()
            .withObjectWriter(writer)
            .withObjectReader(mock(ObjectReader.class))
            .withBuffer(new ByteBufItemSource(createDefaultTestByteBuf(), source -> {}))
            .addAction(action1)
            .addAction(action2)
            .build();

    // when
    bulk.serializeRequest();

    // then
    ArgumentCaptor<BufferedIndex> captor = ArgumentCaptor.forClass(BufferedIndex.class);
    verify(writer, times(2)).writeValue((OutputStream)any(), captor.capture());
    List<BufferedIndex> allValues = captor.getAllValues();
    assertEquals(2, allValues.size());
    assertEquals(index1, allValues.get(0).getIndex());
    assertEquals(index2, allValues.get(1).getIndex());

}
 
Example #25
Source Project: log4j2-elasticsearch   Author: rfoltyns   File: HCBatchOperations.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @return {@code com.fasterxml.jackson.databind.ObjectWriter} to serialize {@link IndexRequest} instances
 */
// FIXME: design - wrap with Serializer(?) to allow other implementations
protected ObjectWriter configuredWriter() {
    return new ExtendedObjectMapper(new MappingJsonFactory())
            .setSerializationInclusion(JsonInclude.Include.NON_EMPTY)
            .addMixIn(IndexRequest.class, IndexRequestMixIn.class)
            .writerFor(IndexRequest.class);
}
 
Example #26
Source Project: jus   Author: apptik   File: JacksonRequest.java    License: Apache License 2.0 5 votes vote down vote up
public <R> JacksonRequest<T> setRequestData(R requestData, ObjectWriter adapter) {
    try {
        super.setRequestData(requestData, new JacksonRequestConverter<R>(adapter));
    } catch (IOException e) {
        throw new RuntimeException("Unable to convert " + requestData + " to NetworkRequest", e);
    }
    //we need to add the headers again as setRequestData overwrote them
    setNetworkRequest(NetworkRequest.Builder.from(getNetworkRequest())
            .setHeader("Accept", "application/json")
            .build());
    return this;
}
 
Example #27
Source Project: api-compiler   Author: googleapis   File: AuthRuleGenerator.java    License: Apache License 2.0 5 votes vote down vote up
/** Verified if the extension schema is correct. */
private static List<Map<String, SecurityRequirementModel>> loadFromSwaggerExtension(
    Object jsonObject) {
  Gson gson = new GsonBuilder().create();
  ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
  Type typeSecurityReqExtension =
      new TypeToken<List<Map<String, SecurityRequirementModel>>>() {}.getType();
  try {
    String jsonString = ow.writeValueAsString(jsonObject);
    return gson.fromJson(jsonString, typeSecurityReqExtension);
  } catch (JsonProcessingException | JsonParseException ex) {
    return null;
  }
}
 
Example #28
Source Project: tutorials   Author: eugenp   File: AdvancedAnnotationsUnitTest.java    License: MIT License 5 votes vote down vote up
@Test
public void whenUsingJsonAppendAnnotation_thenCorrect() throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();

    BeanWithAppend bean = new BeanWithAppend(2, "Bean With Append Annotation");
    ObjectWriter writer = mapper.writerFor(BeanWithAppend.class)
        .withAttribute("version", "1.0");
    String jsonString = writer.writeValueAsString(bean);

    assertThat(jsonString, containsString("version"));
    assertThat(jsonString, containsString("1.0"));
}
 
Example #29
Source Project: servicetalk   Author: apple   File: JacksonSerializationProvider.java    License: Apache License 2.0 5 votes vote down vote up
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 #30
Source Project: powsybl-core   Author: powsybl   File: JsonSensitivityComputationParameters.java    License: Mozilla Public License 2.0 5 votes vote down vote up
/**
 * 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);
    }
}