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

The following examples show how to use com.fasterxml.jackson.databind.JsonNode#isValueNode() . 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: JSONMatchers.java    From arctic-sea with Apache License 2.0 6 votes vote down vote up
protected static boolean describeNodeType(JsonNode item, Description desc) {
    if (item.isTextual()) {
        desc.appendText("was a text node");
    } else if (item.isNumber()) {
        desc.appendText("was a number node");
    } else if (item.isBoolean()) {
        desc.appendText("was a boolean node");
    } else if (item.isValueNode()) {
        desc.appendText("was a value node");
    } else if (item.isObject()) {
        desc.appendText("was a object node");
    } else if (item.isArray()) {
        desc.appendText("was a array node");
    } else if (item.isMissingNode()) {
        desc.appendText("was a missing node");
    } else if (item.isNull()) {
        desc.appendText("was a null node");
    }
    return false;
}
 
Example 2
Source File: BaseType.java    From ovsdb with Eclipse Public License 1.0 6 votes vote down vote up
public static BaseType fromJson(final JsonNode json, final String keyorval) {
    if (json.isValueNode()) {
        return singletonFor(json.asText().trim());
    }

    final JsonNode type = json.get(keyorval);
    if (type == null) {
        throw new TyperException("Not a type");
    }
    if (type.isTextual()) {
        //json like  "string"
        return singletonFor(type.asText());
    }
    if (type.isObject()) {
        //json like  {"type" : "string", "enum": ["set", ["access", "native-tagged"]]}" for key or value
        final JsonNode typeName = type.get("type");
        if (typeName != null) {
            final BaseTypeFactory<?> factory = factoryFor(typeName.asText());
            if (factory != null) {
                return factory.create(type);
            }
        }
    }

    return null;
}
 
Example 3
Source File: ODataJsonDeserializer.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private List<Entity> consumeEntitySetArray(final EdmEntityType edmEntityType, final JsonNode jsonNode,
    final ExpandTreeBuilder expandBuilder) throws DeserializerException {
  if (jsonNode.isArray()) {
    List<Entity> entities = new ArrayList<>();
    for (JsonNode arrayElement : jsonNode) {
      if (arrayElement.isArray() || arrayElement.isValueNode()) {
        throw new DeserializerException("Nested Arrays and primitive values are not allowed for an entity value.",
            DeserializerException.MessageKeys.INVALID_ENTITY);
      }
      EdmEntityType derivedEdmEntityType = (EdmEntityType) getDerivedType(edmEntityType, arrayElement);
      entities.add(consumeEntityNode(derivedEdmEntityType, (ObjectNode) arrayElement, expandBuilder));
    }
    return entities;
  } else {
    throw new DeserializerException("The content of the value tag must be an Array but is not.",
        DeserializerException.MessageKeys.VALUE_TAG_MUST_BE_AN_ARRAY);
  }
}
 
Example 4
Source File: GenericFilterExpander.java    From samantha with MIT License 6 votes vote down vote up
private boolean evaluateFieldFilter(JsonNode value, JsonNode conditions) {
    if (conditions.isArray()) {
        for (JsonNode inVal : conditions) {
            if (!CompareRelation.eq.compare(value, inVal)) {
                return false;
            }
        }
    } else if (conditions.isValueNode()) {
        if (!CompareRelation.eq.compare(value, conditions)) {
            return false;
        }
    } else {
        Iterator<String> conds = conditions.fieldNames();
        while (conds.hasNext()) {
            String cond = conds.next();
            if (!CompareRelation.valueOf(cond).compare(value, conditions.get(cond))) {
                return false;
            }
        }
    }
    return true;
}
 
Example 5
Source File: MappingTest3.java    From jolt with Apache License 2.0 6 votes vote down vote up
/**
 * Demonstrates how to do recursive polymorphic JSON deserialization in Jackson 2.2.
 *
 * Aka specify a Deserializer and "catch" some input, determine what type of Class it
 *  should be parsed too, and then reuse the Jackson infrastructure to recursively do so.
 */
@Override
public QueryFilter deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException {

    ObjectNode root = jp.readValueAsTree();

    // pass in our objectCodec so that the subJsonParser knows about our configured Modules and Annotations
    JsonParser subJsonParser = root.traverse( jp.getCodec() );

    // Check if it is a "RealFilter"
    JsonNode queryParam = root.get("queryParam");
    if ( queryParam != null && queryParam.isValueNode() ) {
        return subJsonParser.readValueAs( RealFilter.class );
    }
    else {
        return subJsonParser.readValueAs( LogicalFilter3.class );
    }
}
 
Example 6
Source File: OpenAPIDeserializer.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
public String getString(String key, ObjectNode node, boolean required, String location, ParseResult result, Set<String> uniqueValues) {
    String value = null;
    JsonNode v = node.get(key);
    if (node == null || v == null) {
        if (required) {
            result.missing(location, key);
            result.invalid();
        }
    } else if (!v.isValueNode()) {
        result.invalidType(location, key, "string", node);
    } else {
        value = v.asText();
        if (uniqueValues != null && !uniqueValues.add(value)) {
            result.unique(location, "operationId");
            result.invalid();
        }
    }
    return value;
}
 
Example 7
Source File: Filter.java    From batfish with Apache License 2.0 6 votes vote down vote up
private static Object extractValue(JsonNode jsonNode, List<String> columns, int index)
    throws JsonProcessingException {
  if (jsonNode.isValueNode()) {
    if (index == columns.size()) { // we should arrive at the ValueNode in the end
      return BatfishObjectMapper.mapper().treeToValue(jsonNode, Object.class);
    } else {
      throw new BatfishException("Column specification is deeper than column value");
    }
  } else {
    if (index < columns.size()) {
      ObjectNode objectNode = (ObjectNode) jsonNode;
      if (objectNode.has(columns.get(index))) {
        return extractValue(objectNode.get(columns.get(index)), columns, index + 1);
      } else {
        throw new BatfishException("Missing sub column: " + columns.get(index));
      }
    } else {
      throw new BatfishException("Column specification is shallower than column value");
    }
  }
}
 
Example 8
Source File: JsonNodeIterator.java    From tutorials with MIT License 5 votes vote down vote up
private void processNode(JsonNode jsonNode, StringBuilder yaml, int depth) {
    if (jsonNode.isValueNode()) {
        yaml.append(jsonNode.asText());
    }
    else if (jsonNode.isArray()) {
        for (JsonNode arrayItem : jsonNode) {
            appendNodeToYaml(arrayItem, yaml, depth, true);
        }
    }
    else if (jsonNode.isObject()) {
        appendNodeToYaml(jsonNode, yaml, depth, false);
    }
}
 
Example 9
Source File: Utils.java    From link-move with Apache License 2.0 5 votes vote down vote up
public static JsonNode unwrapValueNode(List<JsonNodeWrapper> wrappedNode) {
    if (wrappedNode == null || wrappedNode.isEmpty()) {
        return null;
    }
    if (wrappedNode.size() > 1) {
        throw new RuntimeException("Unexpected number of results (must be 0 or 1): " + wrappedNode.size());
    }
    JsonNode valueNode = wrappedNode.get(0).getNode();
    if (!valueNode.isValueNode()) {
        throw new RuntimeException("Expected value node as result, but received: " + valueNode.getNodeType().name());
    }
    return valueNode;
}
 
Example 10
Source File: FreeMarkerTemplateUtils.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
public String getFieldValue(String armTemplate, String fieldName) {
    JsonNode node = convertStringTemplateToJson(armTemplate);
    JsonNode foundNode = node.findValue(fieldName);
    if (foundNode.isValueNode()) {
        return foundNode.asText();
    }
    return null;
}
 
Example 11
Source File: MongoJsonUtils.java    From mica with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static void getLeafNodes(JsonNode jsonNode, JsonNode parentNode, LinkedList<String> deque, List<JsonNodeInfo> list) {
	Iterator<Map.Entry<String, JsonNode>> iterator;
	if (parentNode == null) {
		iterator = jsonNode.fields();
	} else {
		iterator = parentNode.fields();
	}
	// tree 子节点
	while (iterator.hasNext()) {
		Map.Entry<String, JsonNode> entry = iterator.next();
		String fieldName = entry.getKey();
		JsonNode nextNode = entry.getValue();
		// 如果不是值节点
		if (nextNode.isObject()) {
			// 添加到队列尾,先进先出
			deque.addLast(fieldName);
			getLeafNodes(parentNode, nextNode, deque, list);
		}
		// 如果是值节点,也就是到叶子节点了,取叶子节点上级即可
		if (nextNode.isValueNode()) {
			// 封装节点列表
			LinkedList<String> elements = new LinkedList<>(deque);
			// tree 的 叶子节点,此处为引用
			list.add(new JsonNodeInfo(elements, parentNode));
			break;
		}
		// 栈非空时弹出
		if (!deque.isEmpty()) {
			deque.removeLast();
		}
	}
}
 
Example 12
Source File: Json.java    From AsuraFramework with Apache License 2.0 5 votes vote down vote up
/**
 *
 * 获取json传 K-V 的V值只适应于获取叶子节点的V值
 * 注意:如果{"a":"b","c":{"d":"d1","e":{"f","f1"}}}
 * 当 path为c时候,返回:{"d":"d1","e":{"f","f1"}}
 * @param json
 * @param paths
 *
 * @return
 */
public static String getString(@NotNull String json, @Nullable String... paths) {
    JsonNode jsonNode = parseJsonNode(json,  paths);
    if (Check.isNull(jsonNode)) {
        return null;
    }
    if(jsonNode.isValueNode()){
        return jsonNode.textValue();
    }
    return toJsonString(jsonNode);
}
 
Example 13
Source File: HelperJsonUtils.java    From zerocode with Apache License 2.0 5 votes vote down vote up
public static String getContentAsItIsJson(Object bodyContent) {

        if (null == bodyContent) {
            return null;
        }

        final JsonNode bodyJsonNode;
        try {
            /*
             * The bodyContent is a map, because it was read uisng jayway-jaon-path.
             * So needed to be converted into json string.
             */
            final String bodyContentAsString = mapper.writeValueAsString(bodyContent);
            bodyJsonNode = mapper.readValue(bodyContentAsString, JsonNode.class);

            if (bodyJsonNode.isValueNode()) {
                return bodyJsonNode.asText();
            }

            if (bodyJsonNode.size() == 0) {
                return null;
            }

            return bodyJsonNode.toString();

        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

    }
 
Example 14
Source File: JsonDefinitionColumnVisibilityManagement.java    From geowave with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] translateVisibility(final Object visibilityObject, final String fieldName) {
  if (visibilityObject == null) {
    return null;
  }
  try {
    final JsonNode attributeMap = mapper.readTree(visibilityObject.toString());
    final JsonNode field = attributeMap.get(fieldName);
    if ((field != null) && field.isValueNode()) {
      return validate(field.textValue());
    }
    final Iterator<String> attNameIt = attributeMap.fieldNames();
    while (attNameIt.hasNext()) {
      final String attName = attNameIt.next();
      if (fieldName.matches(attName)) {
        final JsonNode attNode = attributeMap.get(attName);
        if (attNode == null) {
          LOGGER.error(
              "Cannot parse visibility expression, JsonNode for attribute "
                  + attName
                  + " was null");
          return null;
        }
        return validate(attNode.textValue());
      }
    }
  } catch (IOException | NullPointerException e) {
    LOGGER.error("Cannot parse visibility expression " + visibilityObject.toString(), e);
  }
  return null;
}
 
Example 15
Source File: ProcessFactory.java    From incubator-taverna-language with Apache License 2.0 5 votes vote down vote up
public static Process createProcess(JsonNode node) {

        Process process = null;

        if(node.isValueNode()) {
            return new Reference(node.asText());
        }

        JsonNode className = node.get(CLASS);
        if(className != null) {
            if(className.asText().equals("Workflow")) {
                process = new WorkflowProcess(node);
            } else if(className.asText().equals("CommandLineTool")) {
                process = new CommandLineTool(node);
            }
        } else {
            JsonNode runNode = node.get(RUN);
            if(runNode.isValueNode()) {
                process = new Reference(runNode.asText());
            } else {
                String runClass = runNode.get(CLASS).asText();
                switch(runClass) {
                    case "CommandLineTool":
                        process = new CommandLineTool(runNode);
                        break;
                    case "Workflow":
                        process = new WorkflowProcess(runNode);
                        break;
                }
            }
        }


        return process;
    }
 
Example 16
Source File: JSONRenderPolicy.java    From poi-tl with Apache License 2.0 4 votes vote down vote up
public List<TextRenderData> convert(JsonNode jsonNode, int level) {
    String indent = "";
    String cindent = "";
    for (int i = 0; i < level; i++) {
        indent += "    ";
        if (i != level - 1) cindent += "    ";
    }
    List<TextRenderData> result = new ArrayList<>();
    if (jsonNode.isValueNode()) {
        JsonNodeType nodeType = jsonNode.getNodeType();
        switch (nodeType) {
        case BOOLEAN:
            // orange
            result.add(new TextRenderData("FFB90F", jsonNode.booleanValue() + ""));
            break;
        case NUMBER:
            // red
            result.add(new TextRenderData("FF6A6A", jsonNode.numberValue() + ""));
            break;
        case NULL:
            // red
            result.add(new TextRenderData("FF6A6A", "null"));
            break;
        case STRING:
            // green
            result.add(new TextRenderData("7CCD7C", "\"" + jsonNode.asText() + "\""));
            break;
        default:
            result.add(new TextRenderData(defaultColor, "\"" + jsonNode.asText() + "\""));
            break;
        }
    } else if (jsonNode.isArray()) {
        result.add(new TextRenderData(defaultColor, "["));
        result.add(new TextRenderData("\n"));
        int size = jsonNode.size();
        for (int k = 0; k < size; k++) {
            JsonNode arrayItem = jsonNode.get(k);
            result.add(new TextRenderData(indent));
            result.addAll(convert(arrayItem, level + 1));
            if (k != size - 1) {
                result.add(new TextRenderData(defaultColor, ","));
            }
            result.add(new TextRenderData("\n"));
        }
        result.add(new TextRenderData(defaultColor, cindent + "]"));
    } else if (jsonNode.isObject()) {
        Iterator<Entry<String, JsonNode>> fields = jsonNode.fields();
        result.add(new TextRenderData(defaultColor, "{"));
        result.add(new TextRenderData("\n"));
        boolean hasNext = fields.hasNext();
        while (true) {
            if (!hasNext) break;
            Entry<String, JsonNode> entry = fields.next();
            result.add(new TextRenderData(defaultColor, indent + "\"" + entry.getKey() + "\": "));
            JsonNode value = entry.getValue();
            result.addAll(convert(value, level + 1));
            hasNext = fields.hasNext();
            if (hasNext) {
                result.add(new TextRenderData(defaultColor, ","));//
            }
            result.add(new TextRenderData("\n"));
        }
        result.add(new TextRenderData(defaultColor, cindent + "}"));
    }

    return result;
}
 
Example 17
Source File: JsonParsingServiceImpl.java    From konker-platform with Apache License 2.0 4 votes vote down vote up
private void addKeys(String currentPath, JsonNode jsonNode, Map<String, JsonPathData> map, List<JsonNodeType> knownTypes) {
    if (jsonNode.isObject()) {
        ObjectNode objectNode = (ObjectNode) jsonNode;
        Iterator<Map.Entry<String, JsonNode>> iterator = objectNode.fields();
        String pathPrefix = currentPath.isEmpty() ? "" : currentPath + ".";

        if (knownTypes == null)
            knownTypes = new ArrayList<>();

        knownTypes.add(JsonNodeType.OBJECT);

        while (iterator.hasNext()) {
            Map.Entry<String, JsonNode> entry = iterator.next();
            addKeys(pathPrefix + entry.getKey(), entry.getValue(), map, new ArrayList<>(knownTypes));
        }
    } else if (jsonNode.isArray()) {
        ArrayNode arrayNode = (ArrayNode) jsonNode;

        if (currentPath.isEmpty())
            currentPath = "root";

        if (knownTypes == null)
            knownTypes = new ArrayList<>();

        knownTypes.add(JsonNodeType.ARRAY);

        for (int i = 0; i < arrayNode.size(); i++) {
            addKeys(currentPath + "." + i, arrayNode.get(i), map, new ArrayList<>(knownTypes));
        }
    } else if (jsonNode.isValueNode()) {
        ValueNode valueNode = (ValueNode) jsonNode;
        if (knownTypes == null)
            knownTypes = new ArrayList<>();
        knownTypes.add(valueNode.getNodeType());
        JsonPathData.JsonPathDataBuilder data = JsonPathData.builder().types(knownTypes);
        switch (valueNode.getNodeType()) {
            case NUMBER: {
                if (valueNode.asText().contains("."))
                    map.put(currentPath, data.value(valueNode.asDouble()).build());
                else
                    map.put(currentPath, data.value(valueNode.asLong()).build());
                break;
            }
            case BOOLEAN: {
                map.put(currentPath, data.value(valueNode.asBoolean()).build());
                break;
            }
            default: {
                map.put(currentPath, data.value(valueNode.asText()).build());
                break;
            }
        }
    }
}
 
Example 18
Source File: ODataJsonDeserializer.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
private Link consumeBindingLink(final String key, final JsonNode jsonNode, final EdmEntityType edmEntityType)
    throws DeserializerException {
  String[] splitKey = key.split(ODATA_ANNOTATION_MARKER);
  String navigationPropertyName = splitKey[0];
  EdmNavigationProperty edmNavigationProperty = edmEntityType.getNavigationProperty(navigationPropertyName);
  if (edmNavigationProperty == null) {
    throw new DeserializerException("Invalid navigationPropertyName: " + navigationPropertyName,
        DeserializerException.MessageKeys.NAVIGATION_PROPERTY_NOT_FOUND, navigationPropertyName);
  }
  Link bindingLink = new Link();
  bindingLink.setTitle(navigationPropertyName);

  if (edmNavigationProperty.isCollection()) {
    assertIsNullNode(key, jsonNode);
    if (!jsonNode.isArray()) {
      throw new DeserializerException("Binding annotation: " + key + " must be an array.",
          DeserializerException.MessageKeys.INVALID_ANNOTATION_TYPE, key);
    }
    List<String> bindingLinkStrings = new ArrayList<>();
    for (JsonNode arrayValue : jsonNode) {
      assertIsNullNode(key, arrayValue);
      if (!arrayValue.isTextual()) {
        throw new DeserializerException("Binding annotation: " + key + " must have string valued array.",
            DeserializerException.MessageKeys.INVALID_ANNOTATION_TYPE, key);
      }
      bindingLinkStrings.add(arrayValue.asText());
    }
    bindingLink.setType(Constants.ENTITY_COLLECTION_BINDING_LINK_TYPE);
    bindingLink.setBindingLinks(bindingLinkStrings);
  } else {
    if (!jsonNode.isValueNode()) {
      throw new DeserializerException("Binding annotation: " + key + " must be a string value.",
          DeserializerException.MessageKeys.INVALID_ANNOTATION_TYPE, key);
    }
    if (edmNavigationProperty.isNullable() && jsonNode.isNull()) {
      bindingLink.setBindingLink(null);
    } else {
      assertIsNullNode(key, jsonNode);
      bindingLink.setBindingLink(jsonNode.asText());        
    }
    bindingLink.setType(Constants.ENTITY_BINDING_LINK_TYPE);
  }
  return bindingLink;
}
 
Example 19
Source File: ObjectKeyExpressionEvaluator.java    From jasperreports with GNU Lesser General Public License v3.0 4 votes vote down vote up
private List<JRJsonNode> goAnywhereDown(JRJsonNode jrJsonNode) {
    if (log.isDebugEnabled()) {
        log.debug("going " + MemberExpression.DIRECTION.ANYWHERE_DOWN + " by " +
                (expression.isWildcard() ?
                        "wildcard" :
                        "key: [" + expression.getObjectKey() + "]") + " on " + jrJsonNode.getDataNode());
    }

    List<JRJsonNode> result = new ArrayList<>();
    Deque<JRJsonNode> stack = new ArrayDeque<>();
    JsonNode initialDataNode = jrJsonNode.getDataNode();

    if (log.isDebugEnabled()) {
        log.debug("initial stack population with: " + initialDataNode);
    }

    // populate the stack initially
    if (initialDataNode.isArray()) {
        for (JsonNode deeper: initialDataNode) {
            stack.addLast(jrJsonNode.createChild(deeper));
        }
    } else {
        stack.push(jrJsonNode);
    }

    while (!stack.isEmpty()) {
        JRJsonNode stackNode = stack.pop();
        JsonNode stackDataNode = stackNode.getDataNode();

        addChildrenToStack(stackNode, stack);

        if (log.isDebugEnabled()) {
            log.debug("processing stack element: " + stackDataNode);
        }

        // process the current stack item
        if (stackDataNode.isObject()) {
            if (log.isDebugEnabled()) {
                log.debug("stack element is object; wildcard: " + expression.isWildcard());
            }

            // if wildcard => only filter the parent; we already added the object keys to the stack
            if (expression.isWildcard()) {
                if (applyFilter(stackNode)) {
                    result.add(stackNode);
                }
            }
            // else go down and filter
            else {
                JRJsonNode deeperNode = goDeeperIntoObjectNode(stackNode, false);
                if (deeperNode != null) {
                    result.add(deeperNode);
                }
            }
        }
        else if (stackDataNode.isValueNode() || stackDataNode.isArray()) {
            if (log.isDebugEnabled()) {
                log.debug("stack element is " + (stackDataNode.isValueNode() ? "value node" : "array") + "; wildcard: " + expression.isWildcard());
            }

            if (expression.isWildcard()) {
                if (applyFilter(stackNode)) {
                    result.add(stackNode);
                }
            }
        }
    }

    return result;
}
 
Example 20
Source File: ODataJsonDeserializer.java    From olingo-odata4 with Apache License 2.0 3 votes vote down vote up
/**
 * Check if JsonNode is a value node (<code>jsonNode.isValueNode()</code>) and if not throw
 * an DeserializerException.
 * @param name name of property which is checked
 * @param jsonNode node which is checked
 * @throws DeserializerException is thrown if json node is not a value node
 */
private void checkForValueNode(final String name, final JsonNode jsonNode) throws DeserializerException {
  if (!jsonNode.isValueNode()) {
    throw new DeserializerException("Invalid value for property: " + name + " must not be an object or array.",
        DeserializerException.MessageKeys.INVALID_JSON_TYPE_FOR_PROPERTY, name);
  }
}