com.fasterxml.jackson.databind.ObjectReader Java Examples
The following examples show how to use
com.fasterxml.jackson.databind.ObjectReader.
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: BlockingResponseHandlerTest.java From log4j2-elasticsearch with Apache License 2.0 | 6 votes |
@Test public void deserializesResponseUsinGivenReader() throws IOException { // given ObjectReader mockedObjectReader = mock(ObjectReader.class); BlockingResponseHandler<Response> handler = new BlockingResponseHandler<>( mockedObjectReader, ex -> null); InputStream inputStream = mock(InputStream.class); // when handler.deserializeResponse(inputStream); // then verify(mockedObjectReader).readValue(any(InputStream.class)); }
Example #2
Source File: ArtifactDeserializer.java From Partner-Center-Java with MIT License | 6 votes |
@Override public Artifact deserialize(JsonParser parser, DeserializationContext ctxt) throws IOException, JsonProcessingException { JsonNode node = parser.readValueAsTree(); ObjectMapper mapper = (ObjectMapper)parser.getCodec(); ObjectReader reader = null; Object target = null; String artifcatType = node.get("artifactType").asText(); System.out.println(artifcatType); if(artifcatType.equalsIgnoreCase("reservedinstance")) { reader = mapper.readerFor(ReservedInstanceArtifact.class); } else { reader = mapper.readerFor(Artifact.class); } target = reader.readValue(node); return (Artifact)target; }
Example #3
Source File: DurationDeserTest.java From jackson-modules-java8 with Apache License 2.0 | 6 votes |
@Test public void testLenientDeserializeFromEmptyString() throws Exception { String key = "duration"; ObjectMapper mapper = newMapper(); ObjectReader objectReader = mapper.readerFor(MAP_TYPE_REF); String dateValAsNullStr = null; String dateValAsEmptyStr = ""; String valueFromNullStr = mapper.writeValueAsString(asMap(key, dateValAsNullStr)); Map<String, Duration> actualMapFromNullStr = objectReader.readValue(valueFromNullStr); Duration actualDateFromNullStr = actualMapFromNullStr.get(key); assertNull(actualDateFromNullStr); String valueFromEmptyStr = mapper.writeValueAsString(asMap(key, dateValAsEmptyStr)); Map<String, Duration> actualMapFromEmptyStr = objectReader.readValue(valueFromEmptyStr); Duration actualDateFromEmptyStr = actualMapFromEmptyStr.get(key); assertEquals("empty string failed to deserialize to null with lenient setting", null, actualDateFromEmptyStr); }
Example #4
Source File: CsvInputStreamMapper.java From pocket-etl with Apache License 2.0 | 6 votes |
/** * Converts an inputStream into an iterator of objects using Jackson CSV mapper. * @param inputStream inputStream in CSV format. * @return An iterator based on the inputStream. */ @Override public Iterator<T> apply(InputStream inputStream) { try { CsvSchema csvSchema = mapper.schemaFor(objectClass); if (columnSeparator != null) { csvSchema = csvSchema.withColumnSeparator(columnSeparator); } ObjectReader reader = mapper.readerFor(objectClass).withFeatures(CsvParser.Feature.FAIL_ON_MISSING_COLUMNS) .with(csvSchema); return reader.readValues(inputStream); } catch (IOException e) { throw new RuntimeException(e); } }
Example #5
Source File: HomeModuleTest.java From crnk-framework with Apache License 2.0 | 6 votes |
@Test public void checkUrlFilteringForRoot() throws IOException { // add filter to include additional parameter `test` JsonApiUrlBuilder urlBuilder = (JsonApiUrlBuilder) boot.getUrlBuilder(); urlBuilder.addPropagatedParameter("test"); // e.g. /api/tasks/history/ HttpRequestContextBase context = Mockito.mock(HttpRequestContextBase.class); Mockito.when(context.getMethod()).thenReturn("GET"); Mockito.when(context.getPath()).thenReturn("/"); Map<String, Set<String>> parameters = new HashMap<>(); parameters.put("test", Sets.newHashSet("foo")); Mockito.when(context.getRequestParameters()).thenReturn(parameters); Mockito.when(context.getRequestHeader(Mockito.eq(HttpHeaders.HTTP_HEADER_ACCEPT))).thenReturn(HttpHeaders.JSON_CONTENT_TYPE); HttpRequestContextBaseAdapter contextAdapter = new HttpRequestContextBaseAdapter(context); HttpRequestDispatcherImpl requestDispatcher = boot.getRequestDispatcher(); HttpResponse response = requestDispatcher.process(contextAdapter).get().get(); ObjectReader reader = boot.getObjectMapper().readerFor(Document.class); String body = new String(response.getBody()); Assert.assertTrue(body.contains("projects?test=foo")); }
Example #6
Source File: ZoneOffsetDeserTest.java From jackson-modules-java8 with Apache License 2.0 | 6 votes |
@Test public void testStrictDeserializeFromEmptyString() throws Exception { final String key = "zoneOffset"; final ObjectMapper mapper = mapperBuilder() .withCoercionConfig(LogicalType.DateTime, cfg -> cfg.setCoercion(CoercionInputShape.EmptyString, CoercionAction.Fail)) .build(); final ObjectReader objectReader = mapper.readerFor(MAP_TYPE_REF); String valueFromNullStr = mapper.writeValueAsString(asMap(key, null)); Map<String, ZoneOffset> actualMapFromNullStr = objectReader.readValue(valueFromNullStr); assertNull(actualMapFromNullStr.get(key)); String valueFromEmptyStr = mapper.writeValueAsString(asMap(key, "")); try { objectReader.readValue(valueFromEmptyStr); fail("Should not pass"); } catch (MismatchedInputException e) { verifyException(e, "Cannot coerce empty String"); verifyException(e, ZoneOffset.class.getName()); } }
Example #7
Source File: JsonMetaInformation.java From crnk-framework with Apache License 2.0 | 6 votes |
protected static <T> T createInterfaceJsonAdapter(Class<T> interfaceClass, JsonNode data, final ObjectMapper mapper) { Class[] interfaces = new Class[] { interfaceClass }; return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), interfaces, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getDeclaringClass().equals(Object.class)) { throw new UnsupportedOperationException("not implemented"); } String name = ClassUtils.getGetterFieldName(method); JsonNode jsonNode = data.get(name); if(jsonNode != null) { Class<?> returnType = method.getReturnType(); ObjectReader objectReader = mapper.readerFor(returnType); return objectReader.readValue(jsonNode); } return null; } }); }
Example #8
Source File: ClientResourceUpsert.java From katharsis-framework with Apache License 2.0 | 6 votes |
protected void setMeta(Resource dataBody, Object instance, ResourceInformation resourceInformation) { ResourceField metaField = resourceInformation.getMetaField(); if (dataBody.getMeta() != null && metaField != null) { JsonNode metaNode = dataBody.getMeta(); Class<?> metaClass = metaField.getType(); ObjectReader metaMapper = objectMapper.readerFor(metaClass); try { Object meta = metaMapper.readValue(metaNode); PropertyUtils.setProperty(instance, metaField.getUnderlyingName(), meta); } catch (IOException e) { throw new ResponseBodyException("failed to parse links information", e); } } }
Example #9
Source File: ProtobufByteStringSerDe.java From dremio-oss with Apache License 2.0 | 6 votes |
/** * Deserialize the given byte string to an object using the given reader, employing the given codec algorithm. * * @param reader object reader * @param byteString byte string to deserialize * @param codec codec * @param logger logger * @param <T> object type of the deserialized object * @return deserialized object * @throws IOException in case of deserialization errors */ public static <T> T readValue(ObjectReader reader, ByteString byteString, Codec codec, Logger logger) throws IOException { if (logger.isTraceEnabled()) { // Costly conversion to UTF-8. Avoid if possible ByteSource bs = new ByteSource() { @Override public InputStream openStream() throws IOException { return codec.decompress(byteString.newInput()); }}; final String value = bs.asCharSource(StandardCharsets.UTF_8).read(); logger.trace("Attempting to read {}", value); // Could reuse the value but to avoid so that logger level doesn't impact the program flow // Since level is trace, user probably doesn't care for performance right now // return reader.readValue(value); } try (InputStream is = codec.decompress(byteString.newInput())) { return reader.readValue(is); } }
Example #10
Source File: JacksonMarshaller.java From nexus-public with Eclipse Public License 1.0 | 6 votes |
@Override public <T> T unmarshall(final Object marshalled, final Class<T> type) throws Exception { checkNotNull(marshalled); checkState(marshalled instanceof Map, "Marshalled data must be a Map; found: %s", marshalled.getClass()); // FIXME: This allows the top-level object to be created, but if any children objects of this are missing // FIXME: ... no-arg CTOR then Jackson will fail to construct them. // FIXME: Is there any way to configure the basic instance creation for Jackson? Object value = instanceCreator.newInstance(type); // performs same basic logic as ObjectMapper.convertValue(Object, Class) helper ObjectReader reader = objectMapper.readerForUpdating(value); TokenBuffer buff = new TokenBuffer(objectMapper, false); objectMapper.writeValue(buff, marshalled); reader.readValue(buff.asParser()); return type.cast(value); }
Example #11
Source File: ZoneIdDeserTest.java From jackson-modules-java8 with Apache License 2.0 | 6 votes |
@Test public void testLenientDeserializeFromEmptyString() throws Exception { String key = "zoneId"; ObjectMapper mapper = newMapper(); ObjectReader objectReader = mapper.readerFor(MAP_TYPE_REF); String valueFromNullStr = mapper.writeValueAsString(asMap(key, null)); Map<String, ZoneId> actualMapFromNullStr = objectReader.readValue(valueFromNullStr); ZoneId actualDateFromNullStr = actualMapFromNullStr.get(key); assertNull(actualDateFromNullStr); String valueFromEmptyStr = mapper.writeValueAsString(asMap(key, "")); Map<String, ZoneId> actualMapFromEmptyStr = objectReader.readValue(valueFromEmptyStr); ZoneId actualDateFromEmptyStr = actualMapFromEmptyStr.get(key); assertEquals("empty string failed to deserialize to null with lenient setting", null, actualDateFromEmptyStr); }
Example #12
Source File: JweTokenSerializer.java From OAuth-2.0-Cookbook with MIT License | 6 votes |
public Map<String, Object> decode(String base64EncodedKey, String content) { try { byte[] decodedKey = Base64.getDecoder().decode(base64EncodedKey); SecretKey key = new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES"); JWEObject jwe = JWEObject.parse(content); jwe.decrypt(new AESDecrypter(key)); ObjectMapper objectMapper = new ObjectMapper(); ObjectReader reader = objectMapper.readerFor(Map.class); return reader.with(DeserializationFeature.USE_LONG_FOR_INTS) .readValue(jwe.getPayload().toString()); } catch (Exception e) { throw new RuntimeException(e); } }
Example #13
Source File: ObjectReaderIT.java From pinpoint with Apache License 2.0 | 6 votes |
@Test public void testReadValue() throws Exception { String json_str = "{\"name\" : \"Jackson\"}"; byte[] json_b = json_str.getBytes(UTF_8); ObjectReader reader = mapper.reader(__POJO.class); __POJO pojo = reader.readValue(json_str); pojo = reader.readValue(json_b); PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance(); verifier.printCache(); Method readval1 = ObjectReader.class.getMethod("readValue", String.class); Method readval2 = ObjectReader.class.getMethod("readValue", byte[].class); verifier.verifyTrace(event("JACKSON", readval1, Expectations.annotation("jackson.json.length", json_str.length()))); verifier.verifyTrace(event("JACKSON", readval2, Expectations.annotation("jackson.json.length", json_b.length))); verifier.verifyTraceCount(0); }
Example #14
Source File: JSONUtil.java From BlogManagePlatform with Apache License 2.0 | 6 votes |
/** * 获取Reader * @author Frodez * @date 2019-05-24 */ @SneakyThrows public static ObjectReader reader(Class<?> parametrized, @Nullable Class<?>... genericClasses) { Assert.notNull(parametrized, "parametrized must not be null"); if (EmptyUtil.yes(genericClasses)) { return singleClassReaderCache.computeIfAbsent(parametrized, (k) -> OBJECT_MAPPER.readerFor(OBJECT_MAPPER.getTypeFactory().constructType( parametrized))); } else { StringBuilder builder = new StringBuilder(parametrized.getName()); for (Class<?> klass : genericClasses) { builder.append(klass.getName()); } return multiClassReaderCache.computeIfAbsent(builder.toString(), (i) -> OBJECT_MAPPER.readerFor(OBJECT_MAPPER.getTypeFactory() .constructParametricType(parametrized, genericClasses))); } }
Example #15
Source File: OffsetDateTimeDeserTest.java From jackson-modules-java8 with Apache License 2.0 | 6 votes |
@Test ( expected = MismatchedInputException.class) public void testStrictDeserializeFromEmptyString() throws Exception { final String key = "OffsetDateTime"; final ObjectMapper mapper = mapperBuilder() .withConfigOverride(OffsetDateTime.class, o -> o.setFormat(JsonFormat.Value.forLeniency(false))) .build(); final ObjectReader objectReader = mapper.readerFor(MAP_TYPE_REF); String valueFromNullStr = mapper.writeValueAsString(asMap(key, null)); Map<String, OffsetDateTime> actualMapFromNullStr = objectReader.readValue(valueFromNullStr); assertNull(actualMapFromNullStr.get(key)); String valueFromEmptyStr = mapper.writeValueAsString(asMap(key, "")); objectReader.readValue(valueFromEmptyStr); }
Example #16
Source File: JsonConverter.java From conf4j with MIT License | 6 votes |
@Override public T fromString(Type type, String value, Map<String, String> attributes) { requireNonNull(type, "type cannot be null"); if (value == null) { return null; } try { JavaType javaType = TypeFactory.defaultInstance().constructType(type); ObjectReader objectReader = objectMapper.readerFor(javaType); return objectReader.readValue(value); } catch (IOException e) { // should never happen throw new IllegalStateException(e); } }
Example #17
Source File: FunqyLambdaBindingRecorder.java From quarkus with Apache License 2.0 | 6 votes |
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 #18
Source File: ObjectMappersTest.java From buck with Apache License 2.0 | 6 votes |
@Test @Parameters(method = "getSerializeAndDeserializePathData") @TestCaseName("canSerializeAndDeserializePath({0}_{1})") public void canSerializeAndDeserializePath(Path path, boolean typed) throws Exception { Obj obj = new Obj(); obj.path = path; ObjectWriter writer = typed ? ObjectMappers.WRITER_WITH_TYPE : ObjectMappers.WRITER; ObjectReader reader = typed ? ObjectMappers.READER_WITH_TYPE : ObjectMappers.READER; String data = writer.writeValueAsString(obj); Obj actual = reader.forType(Obj.class).readValue(data); assertEquals(path, actual.path); }
Example #19
Source File: TapiDeviceHelper.java From onos with Apache License 2.0 | 6 votes |
protected static Set<String> getUuids(DeviceId deviceId, DriverHandler handler) { RestSBController controller = checkNotNull(handler.get(RestSBController.class)); ObjectMapper om = new ObjectMapper(); final ObjectReader reader = om.reader(); InputStream response = controller.get(deviceId, CONN_REQ_GET_API, MediaType.APPLICATION_JSON_TYPE); JsonNode jsonNode; try { jsonNode = reader.readTree(response); if (jsonNode == null) { log.error("JsonNode is null for response {}", response); return ImmutableSet.of(); } return parseTapiGetConnectivityRequest(jsonNode); } catch (IOException e) { log.error("Exception while reading response {}", response, e); return ImmutableSet.of(); } }
Example #20
Source File: LocalTimeDeserTest.java From jackson-modules-java8 with Apache License 2.0 | 6 votes |
@Test( expected = MismatchedInputException.class) public void testStrictDeserializeFromEmptyString() throws Exception { final String key = "localTime"; final ObjectMapper mapper = mapperBuilder() .withConfigOverride(LocalTime.class, c -> c.setFormat(JsonFormat.Value.forLeniency(false))) .build(); final ObjectReader objectReader = mapper.readerFor(MAP_TYPE_REF); String valueFromNullStr = mapper.writeValueAsString(asMap(key, null)); Map<String, LocalTime> actualMapFromNullStr = objectReader.readValue(valueFromNullStr); assertNull(actualMapFromNullStr.get(key)); String valueFromEmptyStr = mapper.writeValueAsString(asMap("date", "")); objectReader.readValue(valueFromEmptyStr); }
Example #21
Source File: JsonLinksInformation.java From crnk-framework with Apache License 2.0 | 5 votes |
/** * Converts this generic links information to the provided type. * * @param linksClass to return * @return links information based on the provided type. */ @Override public <L extends LinksInformation> L as(Class<L> linksClass) { try { if (linksClass.isInterface()) { return JsonMetaInformation.createInterfaceJsonAdapter(linksClass, data, mapper); } ObjectReader reader = mapper.readerFor(linksClass); return reader.readValue(data); } catch (IOException e) { throw new IllegalStateException(e); } }
Example #22
Source File: TestOffsetDateTimeDeserialization.java From jackson-modules-java8 with Apache License 2.0 | 5 votes |
@Test public void testDeserializationAsString03() throws Exception { // // Verify that the offset in the json is preserved when we disable ADJUST_DATES_TO_CONTEXT_TIME_ZONE // ObjectReader reader2 = READER .without(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE); OffsetDateTime parsed = reader2.readValue(aposToQuotes("'2000-01-01T12:00+05:00'")); assertEquals("The value is not correct.", OffsetDateTime.of(2000, 1, 1, 12, 0, 0, 0, ZoneOffset.ofHours(5)), parsed) ; }
Example #23
Source File: ConfigFileReader.java From streamline with Apache License 2.0 | 5 votes |
private Map<String, String> readConfigFromHadoopXmlType(InputStream configFileStream) throws IOException { ObjectReader reader = new XmlMapper().reader(); HadoopXml hadoopXml = reader.forType(HadoopXml.class).readValue(configFileStream); Map<String, String> configMap = new HashMap<>(); for (HadoopXml.HadoopXmlProperty property : hadoopXml.getProperties()) { configMap.put(property.getName(), property.getValue()); } return configMap; }
Example #24
Source File: SensitivityFactorsJsonSerializer.java From powsybl-core with Mozilla Public License 2.0 | 5 votes |
/** * Read sensitivity factors input in JSON format from reader * @param reader The reader to read from * @return The sensitivity factors input created * @throws IOException */ public static List<SensitivityFactor> read(Reader reader) throws IOException { Objects.requireNonNull(reader); ObjectReader objectReader = JsonUtil.createObjectMapper().readerFor(new TypeReference<List<SensitivityFactor>>() { }); return objectReader.readValue(reader); }
Example #25
Source File: HttpJsonDataUtils.java From ais-sdk with Apache License 2.0 | 5 votes |
public static <T> T getResponseObject(HttpResponse response, Class<T> responseType, String jsonRootName) throws IOException { if (!isOKResponded(response)) { throw new IllegalArgumentException("the response status code is not in [200, 300)!"); } ObjectReader reader = objectMapper.readerFor(responseType).withRootName(jsonRootName); return reader.readValue(EntityUtils.toString(response.getEntity(), ContentType.APPLICATION_JSON.getCharset())); }
Example #26
Source File: JsonLoadFlowParametersTest.java From powsybl-core with Mozilla Public License 2.0 | 5 votes |
@Override public DummyExtension deserializeAndUpdate(JsonParser jsonParser, DeserializationContext deserializationContext, DummyExtension parameters) throws IOException { ObjectMapper objectMapper = createMapper(); ObjectReader objectReader = objectMapper.readerForUpdating(parameters); DummyExtension updatedParameters = objectReader.readValue(jsonParser, DummyExtension.class); return updatedParameters; }
Example #27
Source File: LocalDateDeserTest.java From jackson-modules-java8 with Apache License 2.0 | 5 votes |
@Test public void testDeserializationCaseInsensitiveDisabled() throws Throwable { final ObjectMapper mapper = newMapperBuilder() .configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_VALUES, false) .withConfigOverride(LocalDate.class, o -> o.setFormat( JsonFormat.Value.forPattern("dd-MMM-yyyy"))) .build(); ObjectReader reader = mapper.readerFor(LocalDate.class); expectSuccess(reader, LocalDate.of(2000, Month.JANUARY, 1), quote("01-Jan-2000")); }
Example #28
Source File: JacksonUtils.java From native-navigation with MIT License | 5 votes |
/** Convenient way to read a JSON Array String into a List */ public static <T> List<T> readJsonArray(ObjectMapper objectMapper, String value) { ObjectReader reader = JacksonUtils.readerForType(objectMapper, List.class); //noinspection OverlyBroadCatchBlock try { return reader.readValue(value); } catch (IOException e) { throw new RuntimeException(e); } }
Example #29
Source File: RecordTest.java From bitsy with Apache License 2.0 | 5 votes |
public void testDictionaryMaxProperties() throws Exception { ObjectMapper mapper = new ObjectMapper(); ObjectReader reader = mapper.reader(VertexBeanJson.class); String json = "{\"id\":\"40026fee-498a-4cd9-afad-1ae31363c13e\",\"v\":1,\"s\":\"M\",\"p\":{\"a00\":\"00\",\"a01\":\"01\",\"a02\":\"02\",\"a03\":\"03\",\"a04\":\"04\",\"a05\":\"05\",\"a06\":\"06\",\"a07\":\"07\",\"a08\":\"08\",\"a09\":\"09\",\"a10\":\"10\",\"a11\":\"11\",\"a12\":\"12\",\"a13\":\"13\",\"a14\":\"14\",\"a15\":\"15\",\"a16\":\"16\",\"a17\":\"17\",\"a18\":\"18\",\"a19\":\"19\",\"a20\":\"20\",\"a21\":\"21\",\"a22\":\"22\",\"a23\":\"23\",\"a24\":\"24\",\"a25\":\"25\",\"a26\":\"26\",\"a27\":\"27\",\"a28\":\"28\",\"a29\":\"29\",\"a30\":\"30\",\"a31\":\"31\",\"a32\":\"32\",\"a33\":\"33\",\"a34\":\"34\",\"a35\":\"35\",\"a36\":\"36\",\"a37\":\"37\",\"a38\":\"38\",\"a39\":\"39\",\"a40\":\"40\",\"a41\":\"41\",\"a42\":\"42\",\"a43\":\"43\",\"a44\":\"44\",\"a45\":\"45\",\"a46\":\"46\",\"a47\":\"47\",\"a48\":\"48\",\"a49\":\"49\",\"a50\":\"50\"}}"; VertexBeanJson vBean = reader.readValue(json); int count = vBean.getProperties().size(); assertEquals(51, count); }
Example #30
Source File: BarExtSerializer.java From powsybl-core with Mozilla Public License 2.0 | 5 votes |
@Override public BarExt deserializeAndUpdate(JsonParser jsonParser, DeserializationContext deserializationContext, BarExt parameters) throws IOException { ObjectMapper objectMapper = createMapper(); ObjectReader objectReader = objectMapper.readerForUpdating(parameters); BarExt updatedParameters = objectReader.readValue(jsonParser, BarExt.class); return updatedParameters; }