Java Code Examples for com.fasterxml.jackson.databind.ObjectReader#readValue()

The following examples show how to use com.fasterxml.jackson.databind.ObjectReader#readValue() . 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: JacksonMarshaller.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@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 2
Source File: ArtifactDeserializer.java    From Partner-Center-Java with MIT License 6 votes vote down vote up
@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: ZonedDateTimeDeserTest.java    From jackson-modules-java8 with Apache License 2.0 6 votes vote down vote up
@Test
public void testLenientDeserializeFromEmptyString() throws Exception {

    String key = "zoneDateTime";
    ObjectMapper mapper = newMapper();
    ObjectReader objectReader = mapper.readerFor(MAP_TYPE_REF);

    String valueFromNullStr = mapper.writeValueAsString(asMap(key, null));
    Map<String, ZonedDateTime> actualMapFromNullStr = objectReader.readValue(valueFromNullStr);
    ZonedDateTime actualDateFromNullStr = actualMapFromNullStr.get(key);
    assertNull(actualDateFromNullStr);

    String valueFromEmptyStr = mapper.writeValueAsString(asMap(key, ""));
    Map<String, ZonedDateTime> actualMapFromEmptyStr = objectReader.readValue(valueFromEmptyStr);
    ZonedDateTime actualDateFromEmptyStr = actualMapFromEmptyStr.get(key);
    assertEquals("empty string failed to deserialize to null with lenient setting", null, actualDateFromEmptyStr);
}
 
Example 4
Source File: ObjectReaderIT.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
@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 5
Source File: ZoneOffsetDeserTest.java    From jackson-modules-java8 with Apache License 2.0 6 votes vote down vote up
@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 6
Source File: HyMD.java    From metanome-algorithms with Apache License 2.0 5 votes vote down vote up
private MappingConfiguration readConfig(String json) throws AlgorithmConfigurationException {
  try {
    ObjectReader reader = Jackson.createReader(MappingConfiguration.class);
    return reader.readValue(json);
  } catch (IOException e) {
    throw new AlgorithmConfigurationException("Error parsing json config", e);
  }
}
 
Example 7
Source File: LocalDateDeserTest.java    From jackson-modules-java8 with Apache License 2.0 5 votes vote down vote up
private void expectFailure(ObjectReader reader, String json) throws Throwable {
    try {
        reader.readValue(aposToQuotes(json));
        fail("expected DateTimeParseException");
    } catch (JsonProcessingException e) {
        if (e.getCause() == null) {
            throw e;
        }
        if (!(e.getCause() instanceof DateTimeParseException)) {
            throw e.getCause();
        }
    }
}
 
Example 8
Source File: JsonSensitivityComputationParametersTest.java    From powsybl-core with Mozilla Public License 2.0 5 votes vote down vote up
@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 9
Source File: SensitivityComputationResultJsonSerializer.java    From powsybl-core with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Read sensitivity computation results in JSON format from reader
 * @param reader The reader to read from
 * @return The sensitivity computation results created
 * @throws IOException
 */
public static SensitivityComputationResults read(Reader reader) throws IOException {
    Objects.requireNonNull(reader);

    ObjectReader objectReader = JsonUtil.createObjectMapper().readerFor(SensitivityComputationResults.class);
    return objectReader.readValue(reader);
}
 
Example 10
Source File: ElasticsearchConfig.java    From spring-boot-practice with Apache License 2.0 5 votes vote down vote up
@PostConstruct
public void init() throws IOException {
    log.info("Start loading accounts");
    ClasspathResourceLoader loader = new ClasspathResourceLoader();
    ObjectMapper mapper = new ObjectMapper();
    ObjectReader objectReader = mapper.readerFor(Account.class);
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(loader.openResource("import.json")))) {
        String line;
        while ((line = reader.readLine()) != null) {
            Account account = objectReader.readValue(line);
            accountRepository.save(account);
        }
    }
    log.info("Finished loading");
}
 
Example 11
Source File: HttpJsonDataUtils.java    From ais-sdk with Apache License 2.0 5 votes vote down vote up
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 12
Source File: ClientSideState.java    From syndesis with Apache License 2.0 5 votes vote down vote up
static Object deserialize(final Class<?> type, final byte[] pickle) {
    final ObjectReader reader = MAPPER.readerFor(type);

    try {
        return reader.readValue(pickle);
    } catch (final IOException e) {
        throw new IllegalArgumentException("Unable to deserialize given pickle to value", e);
    }
}
 
Example 13
Source File: BarExtSerializer.java    From powsybl-core with Mozilla Public License 2.0 5 votes vote down vote up
@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;
}
 
Example 14
Source File: JacksonUtil.java    From jpmml-model with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
static
public <E extends PMMLObject> E read(Class<? extends E> clazz, InputStream is) throws IOException {
	ObjectMapper objectMapper = createObjectMapper(null);

	ObjectReader objectReader = objectMapper.readerFor(clazz);

	return objectReader.readValue(is);
}
 
Example 15
Source File: AmazonLambdaContext.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public AmazonLambdaContext(HttpURLConnection request, ObjectReader cognitoReader, ObjectReader clientCtxReader)
        throws IOException {
    awsRequestId = request.getHeaderField(LAMBDA_RUNTIME_AWS_REQUEST_ID);
    logGroupName = logGroupName();
    logStreamName = logStreamName();
    functionName = functionName();
    functionVersion = functionVersion();
    invokedFunctionArn = request.getHeaderField(LAMBDA_RUNTIME_INVOKED_FUNCTION_ARN);

    String cognitoIdentityHeader = request.getHeaderField(LAMBDA_RUNTIME_COGNITO_IDENTITY);
    if (cognitoIdentityHeader != null) {
        cognitoIdentity = cognitoReader.readValue(cognitoIdentityHeader);
    }

    String clientContextHeader = request.getHeaderField(LAMBDA_RUNTIME_CLIENT_CONTEXT);
    if (clientContextHeader != null) {
        clientContext = clientCtxReader.readValue(clientContextHeader);
    }

    String functionMemorySize = functionMemorySize();
    memoryLimitInMB = functionMemorySize != null ? Integer.valueOf(functionMemorySize) : 0;

    String runtimeDeadline = request.getHeaderField(LAMBDA_RUNTIME_DEADLINE_MS);
    if (runtimeDeadline != null) {
        runtimeDeadlineMs = Long.valueOf(runtimeDeadline);
    }
    logger = LambdaRuntime.getLogger();
}
 
Example 16
Source File: ClientResourceUpsert.java    From katharsis-framework with Apache License 2.0 5 votes vote down vote up
protected void setLinks(Resource dataBody, Object instance, ResourceInformation resourceInformation) {
	ResourceField linksField = resourceInformation.getLinksField();
	if (dataBody.getLinks() != null && linksField != null) {
		JsonNode linksNode = dataBody.getLinks();
		Class<?> linksClass = linksField.getType();
		ObjectReader linksMapper = objectMapper.readerFor(linksClass);
		try {
			Object links = linksMapper.readValue(linksNode);
			PropertyUtils.setProperty(instance, linksField.getUnderlyingName(), links);
		} catch (IOException e) {
			throw new ResponseBodyException("failed to parse links information", e);
		}
	}
}
 
Example 17
Source File: OrientHttpClientConfigurationEntityAdapter.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void readFields(final ODocument document, final OrientHttpClientConfiguration entity) throws Exception {
  ObjectReader reader = objectMapper.readerForUpdating(entity);
  TokenBuffer buff = new TokenBuffer(objectMapper, false);
  Map<String, Object> fields = document.toMap();

  // strip out id/class synthetics
  fields.remove("@rid");
  fields.remove("@class");

  log.trace("Reading fields: {}", fields);
  objectMapper.writeValue(buff, fields);
  reader.readValue(buff.asParser());
}
 
Example 18
Source File: TestMapMessage.java    From sailfish-core with Apache License 2.0 4 votes vote down vote up
@Test
public void testMapMessageSerializationWithJson() throws IOException {
    MapMessage message = new MapMessage("namespace", "name");
    message.addField("boolean", true);
    message.addField("boolean_array", Arrays.asList(new Boolean[] { true, false }));
    message.addField("byte", (byte) 1);
    message.addField("byte_array", Arrays.asList(new Byte[] { 2, 3, 4 }));
    message.addField("short", (short) 5);
    message.addField("short_array", Arrays.asList(new Short[] { 6, 7, 8 }));
    message.addField("int", 9);
    message.addField("int_array", Arrays.asList(new Integer[] { 10, 11, 12 }));
    message.addField("long", 13l);
    message.addField("long_array", Arrays.asList(new Long[] { 14l, 15l, 16l }));
    message.addField("float", 17.1f);
    message.addField("float_array", Arrays.asList(new Float[] { 18.1f, 19.1f, 20.1f }));
    message.addField("double", 21.1d);
    message.addField("double_array", Arrays.asList(new Double[] { 22.1d, 23.1d, 24.1d }));
    message.addField("bigdecimal", new BigDecimal("25.1"));
    message.addField("bigdecimal_array", Arrays.asList(new BigDecimal[] { new BigDecimal("26.1"), new BigDecimal("27.1"), new BigDecimal("28.1") }));
    message.addField("char", 'a');
    message.addField("char_array", Arrays.asList(new Character[] { 'b', 'c', 'd' }));
    message.addField("string", "ef");
    message.addField("string_array", Arrays.asList(new String[] { "gh", "jk", "lm" }));
    message.addField("localdatetime", DateTimeUtility.nowLocalDateTime());
    message.addField("localdatetime_array", Arrays.asList(new LocalDateTime[] { DateTimeUtility.nowLocalDateTime(), DateTimeUtility.nowLocalDateTime(), DateTimeUtility.nowLocalDateTime() }));
    message.addField("localdate", DateTimeUtility.nowLocalDate());
    message.addField("localdate_array", Arrays.asList(new LocalDate[] { DateTimeUtility.nowLocalDate(), DateTimeUtility.nowLocalDate(), DateTimeUtility.nowLocalDate() }));
    message.addField("localtime", DateTimeUtility.nowLocalTime());
    message.addField("localtime_array", Arrays.asList(new LocalTime[] { DateTimeUtility.nowLocalTime(), DateTimeUtility.nowLocalTime(), DateTimeUtility.nowLocalTime() }));
    
    MsgMetaData metaData = message.getMetaData();
    metaData.setDictionaryURI(SailfishURI.unsafeParse("plugin.dictionary"));
    metaData.setFromService("fromService");
    metaData.setToService("toService");
    metaData.setRawMessage(new byte[] { 1, 2, 3, 4, 5 });
    metaData.setServiceInfo(new ServiceInfo("id", new ServiceName("env", "serviceName")));
    
    MapMessage subMessage = message.cloneMessage();
    message.addField("message", subMessage);
    message.addField("message_array", Arrays.asList(new MapMessage[] { subMessage, subMessage }));
    
    ObjectMapper objectMapper = new ObjectMapper().enableDefaultTyping(DefaultTyping.NON_FINAL)
            .registerModule(new JavaTimeModule());
    ObjectReader reader = objectMapper.reader(IMessage.class);
    ObjectWriter writer = objectMapper.writer();
    
    String json = writer.writeValueAsString(message);
    
    IMessage message2 = reader.readValue(json);
    
    Assert.assertEquals(message, message2);
}
 
Example 19
Source File: PlainJsonDocumentDeserializer.java    From crnk-framework with Apache License 2.0 4 votes vote down vote up
@Override
public PlainJsonDocument deserialize(JsonParser jp, DeserializationContext context) throws IOException {
	JsonNode documentNode = jp.readValueAsTree();

	PlainJsonDocument document = new PlainJsonDocument();
	document.setMeta((ObjectNode) documentNode.get("meta"));
	document.setLinks((ObjectNode) documentNode.get("links"));
	document.setJsonapi((ObjectNode) documentNode.get("jsonapi"));

	ArrayNode errors = (ArrayNode) documentNode.get("errors");
	if (errors != null) {
		ObjectReader errorReader = objectMapper.readerFor(ErrorData.class);
		List<ErrorData> errorDataList = new ArrayList<>();
		for (JsonNode error : errors) {
			ErrorData errorData = errorReader.readValue(error);
			errorDataList.add(errorData);
		}
		document.setErrors(errorDataList);
	}

		Map<ResourceIdentifier, Resource> included = new HashMap<>();

	JsonNode data = documentNode.get("data");
	if (data instanceof ArrayNode) {
		ArrayNode arrayNode = (ArrayNode) data;
		List<Resource> resources = new ArrayList<>();
		for (JsonNode element : arrayNode) {
			resources.add(deserializeResource(element, included));
		}
		document.setData(Nullable.of(resources));
	}
	else if (data instanceof NullNode) {
		document.setData(Nullable.nullValue());
	}
	else if (data != null) {
		Resource resource = deserializeResource(data, included);
		document.setData(Nullable.of(resource));
	}
	else {
		document.setData(Nullable.empty());
	}

	if (!included.isEmpty()) {
		document.setIncluded(new ArrayList<>(included.values()));
	}

	return document;
}
 
Example 20
Source File: JsonConverter.java    From rest-example with Apache License 2.0 3 votes vote down vote up
/**
 * Creates an object of supplied type from supplied JSON string.
 *
 * @param inJsonRepresentation JSON representation from which to create object(s).
 * @param inDestinationType Type of the (root) object to create.
 * @param <T> Destination type.
 * @return Object(s) created from JSON representation.
 * @throws IOException If error occurs creating object(s).
 */
public static <T> T jsonToObject(final String inJsonRepresentation,
    final Class<T> inDestinationType)
    throws IOException {
    final ObjectMapper theJsonObjectMapper = createAndConfigureJsonObjectMapper();
    final ObjectReader theJsonObjectReader = theJsonObjectMapper.readerFor(inDestinationType);
    return theJsonObjectReader.readValue(inJsonRepresentation);
}