Java Code Examples for com.fasterxml.jackson.databind.ObjectMapper#valueToTree()

The following examples show how to use com.fasterxml.jackson.databind.ObjectMapper#valueToTree() . 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: Validate.java    From product-microgateway with Apache License 2.0 6 votes vote down vote up
/**
 * Replace $ref array elements.
 *
 * @param entry Array reference to be replaced from actual value.
 */
private static void generateArraySchemas(Map.Entry<String, JsonNode> entry) {
    JsonNode entryRef;
    JsonNode ref;
    JsonNode schemaProperty;
    if (entry.getValue() != null) {
        schemaProperty = entry.getValue();
        if (schemaProperty == null) {
            return;
        }
        Iterator<JsonNode> arrayElements = schemaProperty.elements();
        List<JsonNode> nodeList = Lists.newArrayList(arrayElements);
        for (int i = 0; i < nodeList.size(); i++) {
            entryRef = nodeList.get(i);
            if (entryRef.has(Constants.SCHEMA_REFERENCE)) {
                ref = extractSchemaObject(entryRef);
                nodeList.remove(i);
                nodeList.add(ref);
            }
        }
        ObjectMapper mapper = new ObjectMapper();
        ArrayNode array = mapper.valueToTree(nodeList);
        entry.setValue(array);
    }
}
 
Example 2
Source File: DocumentMapper.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
public DocumentMapper(ResourceRegistry resourceRegistry, ObjectMapper objectMapper, PropertiesProvider propertiesProvider,
		ResourceFilterDirectory resourceFilterDirectory, ResultFactory resultFactory, Map<String, String> serverInfo,
		boolean client, UrlBuilder urlBuilder) {
	this.propertiesProvider = propertiesProvider;
	this.client = client;
	this.resultFactory = resultFactory;
	this.resourceFilterDirectory = resourceFilterDirectory;

	PreconditionUtil.verify(client || resourceFilterDirectory != null, "filterBehavior necessary on server-side");

	this.util = newDocumentMapperUtil(resourceRegistry, objectMapper, propertiesProvider, urlBuilder);
	this.resourceMapper = newResourceMapper(util, client, objectMapper);
	this.includeLookupSetter = newIncludeLookupSetter(resourceRegistry, resourceMapper, propertiesProvider, objectMapper);

	if (serverInfo != null && !serverInfo.isEmpty()) {
		jsonapi = objectMapper.valueToTree(serverInfo);
	}
}
 
Example 3
Source File: ContextualStoredAsJsonSerializer.java    From Rosetta with Apache License 2.0 5 votes vote down vote up
private String serializeToString(T value, ObjectMapper mapper, SerializerProvider provider) throws IOException {
  try (SegmentedStringWriter sw = new SegmentedStringWriter(new BufferRecycler())) {
    if (trySerializeToWriter(value, mapper, provider, sw)) {
      return sw.getAndClear();
    }
  }

  // fallback on old behavior
  JsonNode tree = mapper.valueToTree(value);
  if (tree.isNull()) {
    return tree.asText();
  } else {
    return mapper.writeValueAsString(tree);
  }
}
 
Example 4
Source File: MetricStore.java    From incubator-nemo with Apache License 2.0 5 votes vote down vote up
private void generatePreprocessedJsonFromMetricEntry(final Map.Entry<String, Object> idToMetricEntry,
                                                     final JsonGenerator jsonGenerator,
                                                     final ObjectMapper objectMapper) throws IOException {
  final JsonNode jsonNode = objectMapper.valueToTree(idToMetricEntry.getValue());
  jsonGenerator.writeFieldName(idToMetricEntry.getKey());
  jsonGenerator.writeStartObject();
  jsonGenerator.writeFieldName("id");
  jsonGenerator.writeString(idToMetricEntry.getKey());
  jsonGenerator.writeFieldName("data");
  jsonGenerator.writeTree(jsonNode);
  jsonGenerator.writeEndObject();
}
 
Example 5
Source File: TestConverting.java    From incubator-taverna-language with Apache License 2.0 5 votes vote down vote up
public JsonNode loadYamlFile(String filename) {

        Yaml reader = new Yaml();
        ObjectMapper mapper = new ObjectMapper();
        JsonNode node = mapper.valueToTree(reader.load(TestWorkflowProcess.class.getResourceAsStream(filename)));

        return node;
    }
 
Example 6
Source File: IdAnnotationModuleTest.java    From immutables with Apache License 2.0 5 votes vote down vote up
@ParameterizedTest
@MethodSource("mappers")
void immutable(ObjectMapper mapper) throws JsonProcessingException {
  // write
  ImmutablePerson person = new PersonGenerator().next().withId("id123");
  ObjectNode node = mapper.valueToTree(person);
  check(node.get("_id").asText()).is("id123");
  check(ImmutableList.copyOf(node.fieldNames())).not().has("id");

  check(mapper.treeToValue(node, Person.class).id()).is("id123");
  check(mapper.treeToValue(node, ImmutablePerson.class).id()).is("id123");
}
 
Example 7
Source File: WriteSingleElementArraysUnwrappedTest.java    From jackson-datatype-protobuf with Apache License 2.0 5 votes vote down vote up
@Test
public void testEnabled() {
  ObjectMapper mapper = objectMapper(true);

  JsonNode node = mapper.valueToTree(getObject());
  assertThat(node.has("bool")).isTrue();
  assertThat(node.get("bool").isBoolean()).isTrue();
  assertThat(node.get("bool").booleanValue()).isFalse();
}
 
Example 8
Source File: PredictLogger.java    From seldon-server with Apache License 2.0 5 votes vote down vote up
public void log(String client,JsonNode input,PredictionServiceResult response)
{
	ObjectMapper mapper = new ObjectMapper();
	JsonNode prediction = mapper.valueToTree(response);
	ObjectNode topNode = mapper.createObjectNode();
	topNode.put("consumer", client);
	topNode.put("input", input);
	topNode.put("prediction", prediction);
	predictLogger.info(topNode.toString());
}
 
Example 9
Source File: TestWorkflowNesting.java    From incubator-taverna-language with Apache License 2.0 5 votes vote down vote up
public JsonNode loadYamlFile(String filename) {

        Yaml reader = new Yaml();
        ObjectMapper mapper = new ObjectMapper();
        JsonNode node = mapper.valueToTree(reader.load(TestWorkflowProcess.class.getResourceAsStream(filename)));

        return node;
    }
 
Example 10
Source File: HealthStatusTest.java    From aerogear-unifiedpush-server with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnJson() throws IOException {
    //given
    HealthStatus status = getHealthStatus();

    //when
    final ObjectMapper mapper = new ObjectMapper();
    final JsonNode value = mapper.valueToTree(status);

    //then
    final JsonNode format = mapper.reader().readTree(getClass().getResourceAsStream("/health-format.json"));

    //because the json file will use int for the 'runtime' field and the model long
    assertThat(value.toString()).isEqualTo(format.toString());
}
 
Example 11
Source File: ProcessInstanceMigrationDocumentConverter.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public JsonNode convertLocalVariablesToJson(ActivityMigrationMapping.OneToOneMapping mapping, ObjectMapper objectMapper) {
    Map<String, Object> activityLocalVariables = mapping.getActivityLocalVariables();
    if (activityLocalVariables != null && !activityLocalVariables.isEmpty()) {
        return objectMapper.valueToTree(activityLocalVariables);
    }
    return null;
}
 
Example 12
Source File: AltNamesConverterTest.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void jsonToTinkerpopConvertsASerializedAltNamesValuesToADbSerializedAsString() throws Exception {
  ObjectMapper objectMapper = new ObjectMapper();

  JsonNode jsonNode = objectMapper.valueToTree(Lists.newArrayList(ALT_NAME_1, ALT_NAME_2));

  String value = instance.jsonToTinkerpop(jsonNode);

  AltNames altNamesValue = objectMapper.readValue(value, AltNames.class);
  assertThat(altNamesValue.list, containsInAnyOrder(ALT_NAME_1, ALT_NAME_2));
}
 
Example 13
Source File: BuildConfigurationSerializationTest.java    From pnc with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldPatchBuildConfiguration() throws PatchBuilderException, IOException, JsonPatchException {
    ObjectMapper mapper = ObjectMapperProvider.getInstance();

    // given
    Instant now = Instant.now();
    Map<String, String> initialParameters = Collections.singletonMap("KEY", "VALUE");
    BuildConfiguration buildConfiguration = BuildConfiguration.builder()
            .id("1")
            .name("name")
            .creationTime(now)
            .parameters(initialParameters)
            .build();

    // when
    BuildConfigurationPatchBuilder patchBuilder = new BuildConfigurationPatchBuilder();
    patchBuilder.replaceName("new name");
    Map<String, String> newParameter = Collections.singletonMap("KEY 2", "VALUE 2");
    patchBuilder.addParameters(newParameter);

    JsonNode targetJson = mapper.valueToTree(buildConfiguration);
    JsonPatch patch = JsonPatch.fromJson(mapper.readValue(patchBuilder.getJsonPatch(), JsonNode.class));
    JsonNode result = patch.apply(targetJson);

    // then
    BuildConfiguration deserialized = mapper.treeToValue(result, BuildConfiguration.class);
    Assert.assertEquals(now, deserialized.getCreationTime());
    Assert.assertEquals("new name", deserialized.getName());

    Map<String, String> finalParameters = new HashMap<>(initialParameters);
    finalParameters.putAll(newParameter);
    assertThat(deserialized.getParameters()).containsAllEntriesOf(finalParameters);
}
 
Example 14
Source File: JsonRpcServerAnnotateMethodVarArgsTest.java    From jsonrpc4j with MIT License 5 votes vote down vote up
@Test
public void callMethodWithVarArgParameters() throws Exception {
	Map<String, Object> paramsMap = new HashMap<>();
	paramsMap.put("argOne", "one");
	paramsMap.put("argTwo", 2);
	paramsMap.put("argThree", "three");
	paramsMap.put("argFour", 4);
	paramsMap.put("argFive", (Object) "five");
	paramsMap.put("argSix", 6.0f);
	paramsMap.put("argSeven", 7d);
	Object[] callParams = new Object[paramsMap.size() * 2];
	int i = 0;
	for (Map.Entry<String, Object> entry : paramsMap.entrySet()) {
		callParams[i++] = entry.getKey();
		callParams[i++] = entry.getValue();
	}

	jsonRpcServerAnnotatedMethod.handleRequest(
		messageWithMapParamsStream("varargObjectMethod", callParams),
		byteArrayOutputStream
	);
	JsonNode res = result();
	ObjectMapper mapper = new ObjectMapper();
	JsonNode resultNode = mapper.readTree(res.asText());
	// params order saved during call, but order not guaranteed
	ObjectNode expectedResult = mapper.valueToTree(paramsMap);
	expectedResult.set("argTwo", mapper.valueToTree(2));
	expectedResult.set("argFour", mapper.valueToTree(4));
	Assert.assertEquals(expectedResult.toString(), resultNode.toString());
}
 
Example 15
Source File: UnifiedPushMessageTest.java    From aerogear-unifiedpush-server with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSerializeMessage() throws IOException {
    //when
    UnifiedPushMessage unifiedPushMessage = new UnifiedPushMessage();

    Message message = new Message();

    message.setAlert("HELLO!");
    message.getApns().setActionCategory("some value");
    message.setSound("default");
    message.setBadge(2);
    message.getApns().setContentAvailable(true);

    final HashMap<String, Object> data = new HashMap<>();
    data.put("key", "value");
    data.put("key2", "other value");
    message.setUserData(data);

    message.setSimplePush("version=123");
    unifiedPushMessage.setMessage(message);

    final Criteria criteria = new Criteria();
    criteria.setAliases(Arrays.asList("someUsername"));
    criteria.setDeviceTypes(Arrays.asList("someDevice"));
    criteria.setCategories(Arrays.asList("someCategories"));
    criteria.setVariants(Arrays.asList("someVariantIDs"));
    unifiedPushMessage.setCriteria(criteria);

    final Config config = new Config();
    config.setTimeToLive(3360);
    unifiedPushMessage.setConfig(config);

    //then
    final ObjectMapper mapper = new ObjectMapper();
    final JsonNode value = mapper.valueToTree(unifiedPushMessage);

    JsonNode format = mapper.reader().readTree(getClass().getResourceAsStream("/message-format.json"));
    assertEquals(format, value);
}
 
Example 16
Source File: ProcessInstanceMigrationDocumentConverter.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
protected static JsonNode convertToJsonUpgradeScript(Script script, ObjectMapper objectMapper) {
    if (script != null) {
        return objectMapper.valueToTree(script);
    }
    return null;
}
 
Example 17
Source File: ObjectMapperHelper.java    From jackson-datatype-protobuf with Apache License 2.0 4 votes vote down vote up
public static JsonNode toTree(ObjectMapper mapper, Object value) {
  return mapper.valueToTree(value);
}
 
Example 18
Source File: AbstractCursorSerializer.java    From usergrid with Apache License 2.0 4 votes vote down vote up
@Override
public JsonNode toNode( final ObjectMapper objectMapper, final T value ) {
    return objectMapper.valueToTree( value );
}
 
Example 19
Source File: ProcessInstanceMigrationDocumentConverter.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
@Override
protected JsonNode convertNewAssigneeToJson(ActivityMigrationMapping.ManyToOneMapping mapping, ObjectMapper objectMapper) {
    return objectMapper.valueToTree(mapping.getWithNewAssignee());
}
 
Example 20
Source File: JsonFilterSpecMapper.java    From crnk-framework with Apache License 2.0 4 votes vote down vote up
private JsonNode serializeValue(Object value) {
	ObjectMapper objectMapper = context.getObjectMapper();
	return objectMapper.valueToTree(value);
}