Java Code Examples for com.fasterxml.jackson.databind.ObjectMapper#writeValueAsBytes()
The following examples show how to use
com.fasterxml.jackson.databind.ObjectMapper#writeValueAsBytes() .
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: TestUtils.java From dhis2-core with BSD 3-Clause "New" or "Revised" License | 6 votes |
public static byte[] convertObjectToJsonBytes( Object object ) throws IOException { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setSerializationInclusion( JsonInclude.Include.NON_NULL ); objectMapper.configure( SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false ); objectMapper.configure( SerializationFeature.FAIL_ON_EMPTY_BEANS, false ); objectMapper.configure( SerializationFeature.WRAP_EXCEPTIONS, true ); objectMapper.setSerializationInclusion( JsonInclude.Include.NON_NULL ); objectMapper.configure( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false ); objectMapper.configure( DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, true ); objectMapper.configure( DeserializationFeature.WRAP_EXCEPTIONS, true ); objectMapper.disable( MapperFeature.AUTO_DETECT_FIELDS ); objectMapper.disable( MapperFeature.AUTO_DETECT_CREATORS ); objectMapper.disable( MapperFeature.AUTO_DETECT_GETTERS ); objectMapper.disable( MapperFeature.AUTO_DETECT_SETTERS ); objectMapper.disable( MapperFeature.AUTO_DETECT_IS_GETTERS ); return objectMapper.writeValueAsBytes( object ); }
Example 2
Source File: BufferedBulkTest.java From log4j2-elasticsearch with Apache License 2.0 | 6 votes |
@Test public void canDeserializeSuccessResponse() throws IOException { // given TestResult testResult = new TestResult(); testResult.errors = false; testResult.took = new Random().nextInt(1000); BufferedBulk.Builder builder = createDefaultTestMockedBuilder(); builder.withObjectReader(new BufferedBulkOperations(mock(PooledItemSourceFactory.class)).configuredReader()); BufferedBulk bulk = builder.build(); ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); InputStream inputStream = new ByteArrayInputStream(mapper.writeValueAsBytes(testResult)); // when BufferedBulkResult result = bulk.deserializeResponse(inputStream); // then assertTrue(result.isSucceeded()); assertEquals(testResult.took, result.getTook()); }
Example 3
Source File: TestJsonInstanceSerializerCompatibility.java From curator with Apache License 2.0 | 6 votes |
@Test public void testForwardCompatibility() throws Exception { OldServiceInstance<TestJsonInstanceSerializer.Payload> oldInstance = new OldServiceInstance<TestJsonInstanceSerializer.Payload>("name", "id", "address", 10, 20, new TestJsonInstanceSerializer.Payload("test"), 0, ServiceType.DYNAMIC, new UriSpec("{a}/b/{c}")); ObjectMapper mapper = new ObjectMapper(); byte[] oldJson = mapper.writeValueAsBytes(oldInstance); JsonInstanceSerializer<TestJsonInstanceSerializer.Payload> serializer = new JsonInstanceSerializer<TestJsonInstanceSerializer.Payload>(TestJsonInstanceSerializer.Payload.class); ServiceInstance<TestJsonInstanceSerializer.Payload> instance = serializer.deserialize(oldJson); Assert.assertEquals(oldInstance.getName(), instance.getName()); Assert.assertEquals(oldInstance.getId(), instance.getId()); Assert.assertEquals(oldInstance.getAddress(), instance.getAddress()); Assert.assertEquals(oldInstance.getPort(), instance.getPort()); Assert.assertEquals(oldInstance.getSslPort(), instance.getSslPort()); Assert.assertEquals(oldInstance.getPayload(), instance.getPayload()); Assert.assertEquals(oldInstance.getRegistrationTimeUTC(), instance.getRegistrationTimeUTC()); Assert.assertEquals(oldInstance.getServiceType(), instance.getServiceType()); Assert.assertEquals(oldInstance.getUriSpec(), instance.getUriSpec()); Assert.assertTrue(instance.isEnabled()); }
Example 4
Source File: TestUtil.java From Spring-5.0-Projects with MIT License | 5 votes |
/** * Convert an object to JSON byte array. * * @param object * the object to convert * @return the JSON byte array * @throws IOException */ public static byte[] convertObjectToJsonBytes(Object object) throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); JavaTimeModule module = new JavaTimeModule(); mapper.registerModule(module); return mapper.writeValueAsBytes(object); }
Example 5
Source File: TestUtil.java From jhipster-microservices-example with Apache License 2.0 | 5 votes |
/** * Convert an object to JSON byte array. * * @param object * the object to convert * @return the JSON byte array * @throws IOException */ public static byte[] convertObjectToJsonBytes(Object object) throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); JavaTimeModule module = new JavaTimeModule(); mapper.registerModule(module); return mapper.writeValueAsBytes(object); }
Example 6
Source File: TestUtil.java From okta-jhipster-microservices-oauth-example with Apache License 2.0 | 5 votes |
/** * Convert an object to JSON byte array. * * @param object * the object to convert * @return the JSON byte array * @throws IOException */ public static byte[] convertObjectToJsonBytes(Object object) throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); JavaTimeModule module = new JavaTimeModule(); mapper.registerModule(module); return mapper.writeValueAsBytes(object); }
Example 7
Source File: AfterburnerModuleJDKSerializabilityTest.java From jackson-modules-base with Apache License 2.0 | 5 votes |
private void _serDeserPointWith(ObjectMapper mapper) throws Exception { final Point input = new Point(); byte[] rawPoint = mapper.writeValueAsBytes(input); Point result = mapper.readValue(rawPoint, Point.class); assertNotNull(result); assertEquals(input.x, result.x); assertEquals(input.y, result.y); }
Example 8
Source File: CBorJsonConverter.java From konker-platform with Apache License 2.0 | 5 votes |
@Override public ServiceResponse<byte[]> fromJson(String json) { try { CBORFactory factory = new CBORFactory(); ObjectMapper mapper = new ObjectMapper(factory); byte[] cborData = mapper.writeValueAsBytes(json); return ServiceResponseBuilder.<byte[]>ok().withResult(cborData).build(); } catch (JsonProcessingException e) { LOGGER.error("Exception converting JSON to CBOR", e); return ServiceResponseBuilder.<byte[]>error().build(); } }
Example 9
Source File: BufferedBulkTest.java From log4j2-elasticsearch with Apache License 2.0 | 5 votes |
@Test public void canDeserializeSuccessWithFailedItemsResponse() throws IOException { // given Random random = new Random(); BulkResultItem bulkResultItem = createTestErrorBulkResultItem(random.nextInt(1000)); int took = random.nextInt(1000); TestResult testResult = new TestResult(); testResult.errors = true; testResult.took = took; testResult.items = new ArrayList<>(); testResult.items.add(bulkResultItem); BufferedBulk.Builder builder = createDefaultTestMockedBuilder(); builder.withObjectReader(new BufferedBulkOperations(mock(PooledItemSourceFactory.class)).configuredReader()); BufferedBulk bulk = builder.build(); ObjectMapper mapper = new ObjectMapper() .setSerializationInclusion(JsonInclude.Include.NON_EMPTY) .addMixIn(BulkResultItem.class, BulkResultItemMixIn.class); InputStream inputStream = new ByteArrayInputStream(mapper.writeValueAsBytes(testResult)); // when BufferedBulkResult result = bulk.deserializeResponse(inputStream); // then assertFalse(result.isSucceeded()); assertEquals(testResult.took, result.getTook()); BulkResultItem resultItem = testResult.items.get(0); assertEquals(bulkResultItem, resultItem); }
Example 10
Source File: TestUtil.java From cubeai with Apache License 2.0 | 5 votes |
/** * Convert an object to JSON byte array. * * @param object * the object to convert * @return the JSON byte array * @throws IOException */ public static byte[] convertObjectToJsonBytes(Object object) throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); JavaTimeModule module = new JavaTimeModule(); mapper.registerModule(module); return mapper.writeValueAsBytes(object); }
Example 11
Source File: MapRecordAccessor.java From fluency with Apache License 2.0 | 5 votes |
@Override public byte[] toMessagePack(ObjectMapper objectMapperForMessagePack) { try { return objectMapperForMessagePack.writeValueAsBytes(map); } catch (JsonProcessingException e) { throw new IllegalStateException("Failed to serialize the map to MessagePack format", e); } }
Example 12
Source File: JacksonJsonCodec.java From camunda-bpm-reactor with Apache License 2.0 | 5 votes |
@Override protected Function<OUT, byte[]> serializer(final ObjectMapper engine) { return new Function<OUT, byte[]>() { @Override public byte[] apply(OUT o) { try { return engine.writeValueAsBytes(o); } catch (JsonProcessingException e) { throw new IllegalArgumentException(e.getMessage(), e); } } }; }
Example 13
Source File: TestUtil.java From okta-jhipster-microservices-oauth-example with Apache License 2.0 | 5 votes |
/** * Convert an object to JSON byte array. * * @param object * the object to convert * @return the JSON byte array * @throws IOException */ public static byte[] convertObjectToJsonBytes(Object object) throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); JavaTimeModule module = new JavaTimeModule(); mapper.registerModule(module); return mapper.writeValueAsBytes(object); }
Example 14
Source File: TestUtil.java From tutorials with MIT License | 5 votes |
/** * Convert an object to JSON byte array. * * @param object * the object to convert * @return the JSON byte array * @throws IOException */ public static byte[] convertObjectToJsonBytes(Object object) throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); JavaTimeModule module = new JavaTimeModule(); mapper.registerModule(module); return mapper.writeValueAsBytes(object); }
Example 15
Source File: MessagePackParserTest.java From secor with Apache License 2.0 | 4 votes |
@Override public void setUp() throws Exception { mConfig = Mockito.mock(SecorConfig.class); Mockito.when(mConfig.getMessageTimestampName()).thenReturn("ts"); Mockito.when(mConfig.getTimeZone()).thenReturn(TimeZone.getTimeZone("UTC")); Mockito.when(TimestampedMessageParser.usingDateFormat(mConfig)).thenReturn("yyyy-MM-dd"); Mockito.when(TimestampedMessageParser.usingHourFormat(mConfig)).thenReturn("HH"); Mockito.when(TimestampedMessageParser.usingMinuteFormat(mConfig)).thenReturn("mm"); Mockito.when(TimestampedMessageParser.usingDatePrefix(mConfig)).thenReturn("dt="); Mockito.when(TimestampedMessageParser.usingHourPrefix(mConfig)).thenReturn("hr="); Mockito.when(TimestampedMessageParser.usingMinutePrefix(mConfig)).thenReturn("min="); mMessagePackParser = new MessagePackParser(mConfig); mObjectMapper = new ObjectMapper(new MessagePackFactory()); timestamp = System.currentTimeMillis(); HashMap<String, Object> mapWithSecondTimestamp = new HashMap<String, Object>(); mapWithSecondTimestamp.put("ts", 1405970352); mMessageWithSecondsTimestamp = new Message("test", 0, 0, null, mObjectMapper.writeValueAsBytes(mapWithSecondTimestamp), timestamp, null); HashMap<String, Object> mapWithMillisTimestamp = new HashMap<String, Object>(); mapWithMillisTimestamp.put("ts", 1405970352123l); mapWithMillisTimestamp.put("isActive", true); mapWithMillisTimestamp.put("email", "[email protected]"); mapWithMillisTimestamp.put("age", 27); mMessageWithMillisTimestamp = new Message("test", 0, 0, null, mObjectMapper.writeValueAsBytes(mapWithMillisTimestamp), timestamp, null); HashMap<String, Object> mapWithMillisFloatTimestamp = new HashMap<String, Object>(); mapWithMillisFloatTimestamp.put("ts", 1405970352123.0); mapWithMillisFloatTimestamp.put("isActive", false); mapWithMillisFloatTimestamp.put("email", "[email protected]"); mapWithMillisFloatTimestamp.put("age", 35); mMessageWithMillisFloatTimestamp = new Message("test", 0, 0, null, mObjectMapper.writeValueAsBytes(mapWithMillisFloatTimestamp), timestamp, null); HashMap<String, Object> mapWithMillisStringTimestamp = new HashMap<String, Object>(); mapWithMillisStringTimestamp.put("ts", "1405970352123"); mapWithMillisStringTimestamp.put("isActive", null); mapWithMillisStringTimestamp.put("email", "[email protected]"); mapWithMillisStringTimestamp.put("age", 67); mMessageWithMillisStringTimestamp = new Message("test", 0, 0, null, mObjectMapper.writeValueAsBytes(mapWithMillisStringTimestamp), timestamp, null); }
Example 16
Source File: PortfolioControllerTest.java From cf-SpringBootTrader with Apache License 2.0 | 4 votes |
private byte[] convertObjectToJson(Object request) throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(Include.NON_NULL); return mapper.writeValueAsBytes(request); }
Example 17
Source File: SerializationTest.java From enmasse with Apache License 2.0 | 4 votes |
@Test public void testSerializeAddress() throws IOException { String uuid = UUID.randomUUID().toString(); Address address = new AddressBuilder() .withNewMetadata() .withNamespace("ns") .withName("as1.a1") .withResourceVersion("1234") .withSelfLink("/my/link") .withCreationTimestamp("my stamp") .withUid(uuid) .addToAnnotations("my", "annotation") .endMetadata() .withNewSpec() .withAddress("addr1") .withAddressSpace("as1") .withType("queue") .withPlan("inmemory") .endSpec() .build(); ObjectMapper mapper = new ObjectMapper(); byte[] serialized = mapper.writeValueAsBytes(address); Address deserialized = mapper.readValue(serialized, Address.class); assertThat(deserialized, is(address)); assertThat(Address.extractAddressSpace(deserialized), is(Address.extractAddressSpace(address))); assertThat(deserialized.getSpec().getType(), is(address.getSpec().getType())); assertThat(deserialized.getSpec().getPlan(), is(address.getSpec().getPlan())); assertThat(deserialized.getSpec().getAddress(), is(address.getSpec().getAddress())); assertThat(deserialized.getMetadata().getName(), is(address.getMetadata().getName())); assertThat(deserialized.getMetadata().getUid(), is(address.getMetadata().getUid())); assertThat(deserialized.getMetadata().getResourceVersion(), is(address.getMetadata().getResourceVersion())); assertThat(deserialized.getMetadata().getSelfLink(), is(address.getMetadata().getSelfLink())); assertThat(deserialized.getMetadata().getCreationTimestamp(), is(address.getMetadata().getCreationTimestamp())); assertThat(deserialized.getMetadata().getAnnotations(), is(address.getMetadata().getAnnotations())); }
Example 18
Source File: AccountsControllerTest.java From cf-SpringBootTrader with Apache License 2.0 | 4 votes |
private byte[] convertObjectToJson(Object request) throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(Include.NON_NULL); return mapper.writeValueAsBytes(request); }
Example 19
Source File: TestUtils.java From JiwhizBlogWeb with Apache License 2.0 | 4 votes |
public static byte[] convertObjectToJsonBytes(Object object) throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); return mapper.writeValueAsBytes(object); }
Example 20
Source File: RPCRequestBody.java From incubator-tuweni with Apache License 2.0 | 2 votes |
/** * * @param objectMapper the object mapper to serialize to bytes with * @return the bytes representation of this RPC request body. The request is first encoded into JSON, then from JSON * to a byte array * @throws JsonProcessingException thrown if there is a problem transforming the object to JSON. */ public Bytes asBytes(ObjectMapper objectMapper) throws JsonProcessingException { byte[] bytes = objectMapper.writeValueAsBytes(this); return Bytes.wrap(bytes); }