Java Code Examples for com.fasterxml.jackson.databind.JsonNode#isObject()

The following examples show how to use com.fasterxml.jackson.databind.JsonNode#isObject() . 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: JsonUtils.java    From jackson-jsonld with MIT License 6 votes vote down vote up
public static JsonNode merge(JsonNode mainNode, JsonNode updateNode) {

        Iterator<String> fieldNames = updateNode.fieldNames();
        while (fieldNames.hasNext()) {

            String fieldName = fieldNames.next();
            JsonNode jsonNode = mainNode.get(fieldName);
            // if field exists and is an embedded object
            if (jsonNode != null && jsonNode.isObject()) {
                merge(jsonNode, updateNode.get(fieldName));
            }
            else {
                if (mainNode instanceof ObjectNode) {
                    // Overwrite field
                    JsonNode value = updateNode.get(fieldName);
                    ((ObjectNode) mainNode).set(fieldName, value);
                }
            }

        }

        return mainNode;
    }
 
Example 2
Source File: ForExpression.java    From jslt with Apache License 2.0 6 votes vote down vote up
public JsonNode apply(Scope scope, JsonNode input) {
  JsonNode array = valueExpr.apply(scope, input);
  if (array.isNull())
    return NullNode.instance;
  else if (array.isObject())
    array = NodeUtils.convertObjectToArray(array);
  else if (!array.isArray())
    throw new JsltException("For loop can't iterate over " + array, location);

  ArrayNode result = NodeUtils.mapper.createArrayNode();
  for (int ix = 0; ix < array.size(); ix++) {
    JsonNode value = array.get(ix);

    // must evaluate lets over again for each value because of context
    if (lets.length > 0)
      NodeUtils.evalLets(scope, value, lets);

    if (ifExpr == null || NodeUtils.isTrue(ifExpr.apply(scope, value)))
      result.add(loopExpr.apply(scope, value));
  }
  return result;
}
 
Example 3
Source File: EventCsvDownload.java    From konker-platform with Apache License 2.0 6 votes vote down vote up
public void jsonToMap(String currentPath, JsonNode jsonNode, Map<String, String> map) {
	if (jsonNode.isObject()) {
		ObjectNode objectNode = (ObjectNode) jsonNode;
		Iterator<Entry<String, JsonNode>> iter = objectNode.fields();
		String pathPrefix = currentPath.isEmpty() ? "" : currentPath + ".";
		
		while (iter.hasNext()) {
			Entry<String, JsonNode> entry = iter.next();
			jsonToMap(pathPrefix + entry.getKey(), entry.getValue(), map);
		}
	} else if (jsonNode.isArray()) {
		ArrayNode arrayNode = (ArrayNode) jsonNode;
		for (int i = 0; i < arrayNode.size(); i++) {
			jsonToMap(currentPath + "." + i, arrayNode.get(i), map);
		}
	} else if (jsonNode.isValueNode()) {
		ValueNode valueNode = (ValueNode) jsonNode;
		map.put(currentPath, valueNode.asText());
	}
}
 
Example 4
Source File: PathsReader.java    From smallrye-open-api with Apache License 2.0 6 votes vote down vote up
/**
 * Reads the {@link Paths} OpenAPI nodes.
 * 
 * @param node json object
 * @return Paths model
 */
public static Paths readPaths(final JsonNode node) {
    if (node == null || !node.isObject()) {
        return null;
    }
    // LOG ...
    Paths paths = new PathsImpl();
    for (Iterator<String> fieldNames = node.fieldNames(); fieldNames.hasNext();) {
        String fieldName = fieldNames.next();
        if (ExtensionReader.isExtensionField(fieldName)) {
            continue;
        }
        paths.addPathItem(fieldName, readPathItem(node.get(fieldName)));
    }
    ExtensionReader.readExtensions(node, paths);
    return paths;
}
 
Example 5
Source File: TypeFactory.java    From json-schema-validator with Apache License 2.0 6 votes vote down vote up
public static JsonType getValueNodeType(JsonNode node) {
    if (node.isContainerNode()) {
        if (node.isObject())
            return JsonType.OBJECT;
        if (node.isArray())
            return JsonType.ARRAY;
        return JsonType.UNKNOWN;
    }

    if (node.isValueNode()) {
        if (node.isTextual())
            return JsonType.STRING;
        if (node.isIntegralNumber())
            return JsonType.INTEGER;
        if (node.isNumber())
            return JsonType.NUMBER;
        if (node.isBoolean())
            return JsonType.BOOLEAN;
        if (node.isNull())
            return JsonType.NULL;
        return JsonType.UNKNOWN;
    }

    return JsonType.UNKNOWN;
}
 
Example 6
Source File: JsonUtil.java    From besu with Apache License 2.0 6 votes vote down vote up
public static Optional<ObjectNode> getObjectNode(
    final ObjectNode json, final String fieldKey, final boolean strict) {
  final JsonNode obj = json.get(fieldKey);
  if (obj == null || obj.isNull()) {
    return Optional.empty();
  }

  if (!obj.isObject()) {
    if (strict) {
      validateType(obj, JsonNodeType.OBJECT);
    } else {
      return Optional.empty();
    }
  }

  return Optional.of((ObjectNode) obj);
}
 
Example 7
Source File: JsonFlattenConverter.java    From cloud-config with MIT License 6 votes vote down vote up
private void addKeys(String currentPath, JsonNode jsonNode, Map<Object, Object> props) {
    if (jsonNode.isObject()) {
        ObjectNode objectNode = (ObjectNode) jsonNode;
        Iterator<Map.Entry<String, JsonNode>> iter = objectNode.fields();
        String pathPrefix = currentPath.isEmpty() ? "" : currentPath + ".";

        while (iter.hasNext()) {
            Map.Entry<String, JsonNode> entry = iter.next();
            addKeys(pathPrefix + entry.getKey(), entry.getValue(), props);
        }
    } else if (jsonNode.isArray()) {
        ArrayNode arrayNode = (ArrayNode) jsonNode;
        for (int i = 0; i < arrayNode.size(); i++) {
            addKeys(currentPath + "[" + i + "]", arrayNode.get(i), props);
        }
    } else if (jsonNode.isValueNode()) {
        ValueNode valueNode = (ValueNode) jsonNode;
        if(isAllowOverride || !props.containsKey(currentPath))
            props.put(currentPath, valueNode.asText());
    }
}
 
Example 8
Source File: ParameterReader.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
/**
 * Reads the {@link Parameter} OpenAPI nodes.
 * 
 * @param node json map of Parameters
 * @return Map of Parameter model
 */
public static Map<String, Parameter> readParameters(final JsonNode node) {
    if (node == null || !node.isObject()) {
        return null;
    }
    IoLogging.log.jsonMap("Parameters");
    Map<String, Parameter> parameters = new LinkedHashMap<>();
    for (Iterator<String> fieldNames = node.fieldNames(); fieldNames.hasNext();) {
        String fieldName = fieldNames.next();
        JsonNode childNode = node.get(fieldName);
        parameters.put(fieldName, readParameter(childNode));
    }

    return parameters;
}
 
Example 9
Source File: Config.java    From digdag with Apache License 2.0 5 votes vote down vote up
public Config getNested(String key)
{
    JsonNode value = getNode(key);
    if (value == null) {
        throw new ConfigException("Parameter '"+key+"' is required but not set");
    }
    if (!value.isObject()) {
        throw new ConfigException("Parameter '"+key+"' must be an object");
    }
    return new Config(mapper, (ObjectNode) value);
}
 
Example 10
Source File: AdminConfigFile.java    From glowroot with Apache License 2.0 5 votes vote down vote up
private static void upgradeLdapIfNeeded(ObjectNode adminRootObjectNode) {
    JsonNode ldapNode = adminRootObjectNode.get("ldap");
    if (ldapNode == null || !ldapNode.isObject()) {
        return;
    }
    ObjectNode ldapObjectNode = (ObjectNode) ldapNode;
    JsonNode passwordNode = ldapObjectNode.remove("password");
    if (passwordNode != null) {
        // upgrade from 0.11.1 to 0.12.0
        ldapObjectNode.set("encryptedPassword", passwordNode);
    }
}
 
Example 11
Source File: Input.java    From zentity with Apache License 2.0 5 votes vote down vote up
/**
 * Parse and validate the entity model from the 'model' field of the request body.
 *
 * @param requestBody The request body.
 * @return The parsed "model" field from the request body, or an object from ".zentity-models" index.
 * @throws IOException
 * @throws ValidationException
 */
public static Model parseEntityModel(JsonNode requestBody) throws IOException, ValidationException {
    if (!requestBody.has("model"))
        throw new ValidationException("The 'model' field is missing from the request body while 'entity_type' is undefined.");
    JsonNode model = requestBody.get("model");
    if (!model.isObject())
        throw new ValidationException("Entity model must be an object.");
    return new Model(model.toString());
}
 
Example 12
Source File: ObservationDecoder.java    From arctic-sea with Apache License 2.0 5 votes vote down vote up
protected OmObservation decodeJSON(JsonNode node)
        throws DecodingException {
    if (node.isObject()) {
        OmObservation o = new OmObservation();
        o.setIdentifier(parseIdentifier(node));
        o.setValidTime(parseValidTime(node));
        o.setResultTime(parseResultTime(node));
        o.setValue(parseValue(node));
        o.setParameter(parseParameter(node));
        o.setObservationConstellation(parseObservationConstellation(node));
        return o;
    } else {
        return null;
    }
}
 
Example 13
Source File: DynamoDocumentStoreTemplate.java    From Cheddar with Apache License 2.0 5 votes vote down vote up
public JsonNode merge(final JsonNode newNode, final JsonNode oldNode) {
    final Set<String> allFieldNames = new HashSet<>();
    final Iterator<String> newNodeFieldNames = oldNode.fieldNames();
    while (newNodeFieldNames.hasNext()) {
        allFieldNames.add(newNodeFieldNames.next());
    }
    final Iterator<String> oldNodeFieldNames = oldNode.fieldNames();
    while (oldNodeFieldNames.hasNext()) {
        allFieldNames.add(oldNodeFieldNames.next());
    }
    final JsonNode mergedNode = newNode.deepCopy();
    for (final String fieldName : allFieldNames) {
        final JsonNode newNodeValue = newNode.get(fieldName);
        final JsonNode oldNodeValue = oldNode.get(fieldName);
        if (newNodeValue == null && oldNodeValue == null) {
            logger.trace("Skipping (both null): " + fieldName);
        } else if (newNodeValue == null && oldNodeValue != null) {
            logger.trace("Using old (new is null): " + fieldName);
            ((ObjectNode) mergedNode).set(fieldName, oldNodeValue);
        } else if (newNodeValue != null && oldNodeValue == null) {
            logger.trace("Using new (old is null): " + fieldName);
            ((ObjectNode) mergedNode).set(fieldName, newNodeValue);
        } else {
            logger.trace("Using new: " + fieldName);
            if (oldNodeValue.isObject()) {
                ((ObjectNode) mergedNode).set(fieldName, merge(newNodeValue, oldNodeValue));
            } else {
                ((ObjectNode) mergedNode).set(fieldName, newNodeValue);
            }
        }
    }
    return mergedNode;
}
 
Example 14
Source File: JsonDeserializer.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private Map.Entry<PropertyType, EdmTypeInfo> guessPropertyType(final JsonNode node) {
  PropertyType type;
  String typeExpression = null;

  if (node.isValueNode() || node.isNull()) {
    type = PropertyType.PRIMITIVE;
    typeExpression = guessPrimitiveTypeKind(node).getFullQualifiedName().toString();
  } else if (node.isArray()) {
    type = PropertyType.COLLECTION;
    if (node.has(0) && node.get(0).isValueNode()) {
      typeExpression = "Collection(" + guessPrimitiveTypeKind(node.get(0)) + ')';
    }
  } else if (node.isObject()) {
    if (node.has(Constants.ATTR_TYPE)) {
      type = PropertyType.PRIMITIVE;
      typeExpression = "Edm.Geography" + node.get(Constants.ATTR_TYPE).asText();
    } else {
      type = PropertyType.COMPLEX;
    }
  } else {
    type = PropertyType.EMPTY;
  }

  final EdmTypeInfo typeInfo = typeExpression == null ? null :
    new EdmTypeInfo.Builder().setTypeExpression(typeExpression).build();
  return new SimpleEntry<>(type, typeInfo);
}
 
Example 15
Source File: ProvisionedThroughputUnmarshaller.java    From bce-sdk-java with Apache License 2.0 5 votes vote down vote up
@Override
public ProvisionedThroughputDescription unmarshall(JsonNode jsonObj) throws Exception {
    if (!jsonObj.isObject()) {
        throw new BceClientException(
                "input json object is not an object");
    }
    ProvisionedThroughputDescription provision = new ProvisionedThroughputDescription();
    try {
        JsonNode decTimeObj = jsonObj.get(MolaDbConstants.JSON_LAST_DECREASE_TIME);
        JsonNode incTimeObj = jsonObj.get(MolaDbConstants.JSON_LAST_INCREASE_TIME);
        JsonNode decTodayObj = jsonObj.get(MolaDbConstants.JSON_NUM_DECREASE_TODAY);
        JsonNode readCapObj = jsonObj.get(MolaDbConstants.JSON_READ_CAPACITY_UNITS);
        JsonNode writeCapObj = jsonObj.get(MolaDbConstants.JSON_WRITE_CAPACITY_UNITS);
        DateFormat dateParser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        if (decTimeObj != null) {
            provision.setLastDescreaseDateTime(dateParser.parse(decTimeObj.asText()));
        }
        if (incTimeObj != null) {
            provision.setLastIncreaseDateTime(dateParser.parse(incTimeObj.asText()));
        }
        if (decTodayObj != null) {
            provision.setNumberOfDecreasesToday(decTodayObj.asInt());
        }
        provision.setReadCapacityUnits(readCapObj.asLong());
        provision.setWriteCapacityUnits(writeCapObj.asLong());
    } catch (Exception e) {
        throw new BceClientException("Invalid responseContent:" + jsonObj.toString() 
                                     + " meet exception:" + e.toString());
    }
    return provision;
}
 
Example 16
Source File: ODataJsonDeserializer.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private ObjectNode parseJsonTree(final InputStream stream) throws IOException, DeserializerException {
  ObjectMapper objectMapper = new ObjectMapper();
  objectMapper.configure(DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY, true);
  JsonParser parser = new JsonFactory(objectMapper).createParser(stream);
  final JsonNode tree = parser.getCodec().readTree(parser);
  if (tree == null || !tree.isObject()) {
    throw new DeserializerException("Invalid JSON syntax.",
        DeserializerException.MessageKeys.JSON_SYNTAX_EXCEPTION);
  }
  return (ObjectNode) tree;
}
 
Example 17
Source File: ModulationWebResource.java    From onos with Apache License 2.0 4 votes vote down vote up
public void decode(ObjectNode json) {
    if (json == null || !json.isObject()) {
        throw new IllegalArgumentException(JSON_INVALID);
    }

    JsonNode devicesNode = json.get(DEVICES);
    if (!devicesNode.isObject()) {
        throw new IllegalArgumentException(JSON_INVALID);
    }

    Iterator<Map.Entry<String, JsonNode>> deviceEntries = devicesNode.fields();
    while (deviceEntries.hasNext()) {
        Map.Entry<String, JsonNode> deviceEntryNext = deviceEntries.next();
        String deviceId = deviceEntryNext.getKey();
        ModulationConfig<Object> modulationConfig = getModulationConfig(deviceId);
        JsonNode portsNode = deviceEntryNext.getValue();
        if (!portsNode.isObject()) {
            throw new IllegalArgumentException(JSON_INVALID);
        }

        Iterator<Map.Entry<String, JsonNode>> portEntries = portsNode.fields();
        while (portEntries.hasNext()) {
            Map.Entry<String, JsonNode> portEntryNext = portEntries.next();
            PortNumber portNumber = PortNumber.portNumber(portEntryNext.getKey());
            JsonNode componentsNode = portEntryNext.getValue();
            Iterator<Map.Entry<String, JsonNode>> componentEntries = componentsNode.fields();
            while (componentEntries.hasNext()) {
                Direction direction = null;
                Map.Entry<String, JsonNode> componentEntryNext = componentEntries.next();
                try {
                    direction = Direction.valueOf(componentEntryNext.getKey().toUpperCase());
                } catch (IllegalArgumentException e) {
                    // TODO: Handle other components
                }

                JsonNode bitRateNode = componentEntryNext.getValue();
                if (!bitRateNode.isObject()) {
                    throw new IllegalArgumentException(JSON_INVALID);
                }
                Long targetBitRate = bitRateNode.get(TARGET_BITRATE).asLong();
                if (direction != null) {
                    modulationConfig.setModulationScheme(portNumber, direction, targetBitRate);
                }
            }
        }
    }
}
 
Example 18
Source File: Resolver.java    From zentity with Apache License 2.0 4 votes vote down vote up
private void validateObject(JsonNode object) throws ValidationException {
    if (!object.isObject())
        throw new ValidationException("'resolvers." + this.name + "' must be an object.");
    if (object.size() == 0)
        throw new ValidationException("'resolvers." + this.name + "' is empty.");
}
 
Example 19
Source File: RetryControl.java    From digdag with Apache License 2.0 4 votes vote down vote up
private RetryControl(Config config, Config stateParams, boolean enableByDefault)
{

    this.stateParams = stateParams;
    this.retryCount = stateParams.get("retry_count", int.class, 0);

    final JsonNode retryNode = config.getInternalObjectNode().get("_retry");
    try {
        if (retryNode == null) {  // No _retry description. default.
            this.retryLimit = enableByDefault ? 3 : 0;
            this.retryInterval = 0;
            this.maxRetryInterval = Optional.absent();
            this.retryIntervalType = RetryIntervalType.CONSTATNT;
        }
        else if (retryNode.isNumber() || retryNode.isTextual()) {  // Only limit is set.
            // If set as variable ${..}, the value become text. Here uses Config.get(type, key)
            // to get retryLimit so that text is also accepted.
            this.retryLimit = config.get("_retry", int.class);
            this.retryInterval = 0;
            this.maxRetryInterval = Optional.absent();
            this.retryIntervalType = RetryIntervalType.CONSTATNT;
        }
        else if (retryNode.isObject()) {  // json format
            Config retry = config.getNested("_retry");
            this.retryLimit = retry.get("limit", int.class);
            this.retryInterval = retry.getOptional("interval", int.class).or(0).intValue();
            this.maxRetryInterval = retry.getOptional("max_interval", int.class);
            this.retryIntervalType = retry.getOptional("interval_type", String.class)
                .transform(RetryIntervalType::find)
                .or(RetryIntervalType.CONSTATNT);
        }
        else {  // Unknown format
            throw new ConfigException(String.format("Invalid _retry format:%s", retryNode.toString()));
        }
    }
    catch(NumberFormatException nfe) {
        throw new ConfigException(nfe);
    }
    catch(ConfigException ce) {
        throw ce;
    }
}
 
Example 20
Source File: JSONFormatterPdxToJsonConverter.java    From spring-boot-data-geode with Apache License 2.0 2 votes vote down vote up
/**
 * Null-safe method to determine if the given {@link JsonNode} represents a valid {@link String JSON} object.
 *
 * @param node {@link JsonNode} to evaluate.
 * @return a boolean valued indicating whether the given {@link JsonNode} is a valid {@link ObjectNode}.
 * @see com.fasterxml.jackson.databind.node.ObjectNode
 * @see com.fasterxml.jackson.databind.JsonNode
 */
boolean isObjectNode(@Nullable JsonNode node) {
	return node != null && (node.isObject() || node instanceof ObjectNode);
}