Java Code Examples for com.fasterxml.jackson.databind.JsonNode#getNodeType()
The following examples show how to use
com.fasterxml.jackson.databind.JsonNode#getNodeType() .
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: TemporaryJobBuilder.java From helios with Apache License 2.0 | 6 votes |
private TemporaryJobBuilder imageFromInfoJson(final String json, final String source) { try { final JsonNode info = Json.readTree(json); final JsonNode imageNode = info.get("image"); if (imageNode == null) { fail("Missing image field in image info: " + source); } if (imageNode.getNodeType() != STRING) { fail("Bad image field in image info: " + source); } final String image = imageNode.asText(); return image(image); } catch (IOException e) { throw new AssertionError("Failed to parse image info: " + source, e); } }
Example 2
Source File: GenerateBlockchainConfig.java From besu with Apache License 2.0 | 6 votes |
/** * Imports a single public key. * * @param publicKeyJson The public key. */ private void importPublicKey(final JsonNode publicKeyJson) { if (publicKeyJson.getNodeType() != JsonNodeType.STRING) { throw new IllegalArgumentException( "Invalid key json of type: " + publicKeyJson.getNodeType()); } final String publicKeyText = publicKeyJson.asText(); try { final SECP256K1.PublicKey publicKey = SECP256K1.PublicKey.create(Bytes.fromHexString(publicKeyText)); writeKeypair(publicKey, null); LOG.info("Public key imported from configuration.({})", publicKey.toString()); } catch (final IOException e) { LOG.error("An error occurred while trying to import node public key.", e); } }
Example 3
Source File: JsonSerializable.java From azure-cosmosdb-java with MIT License | 6 votes |
static Object getValue(JsonNode value) { if (value.isValueNode()) { switch (value.getNodeType()) { case BOOLEAN: return value.asBoolean(); case NUMBER: if (value.isInt()) { return value.asInt(); } else if (value.isLong()) { return value.asLong(); } else if (value.isDouble()) { return value.asDouble(); } case STRING : return value.asText(); } } return value; }
Example 4
Source File: TTextProtocol.java From armeria with Apache License 2.0 | 6 votes |
@Override public int readI32() throws TException { final Class<?> fieldClass = getCurrentFieldClassIfIs(TEnum.class); if (fieldClass != null) { // Enum fields may be set by string, even though they represent integers. getCurrentContext().read(); final JsonNode elem = getCurrentContext().getCurrentChild(); if (elem.isInt()) { return TypedParser.INTEGER.readFromJsonElement(elem); } else if (elem.isTextual()) { // All TEnum are enums @SuppressWarnings({ "unchecked", "rawtypes" }) final TEnum tEnum = (TEnum) Enum.valueOf((Class<Enum>) fieldClass, TypedParser.STRING.readFromJsonElement(elem)); return tEnum.getValue(); } else { throw new TTransportException("invalid value type for enum field: " + elem.getNodeType() + " (" + elem + ')'); } } else { return readNameOrValue(TypedParser.INTEGER); } }
Example 5
Source File: UtilsValidator.java From SkaETL with Apache License 2.0 | 6 votes |
public static <T> T get(JsonNode jsonValue, String key) { if (!jsonValue.hasNonNull(key)) { return null; } JsonNode jsonNode = JSONUtils.getInstance().at(jsonValue, key); switch (jsonNode.getNodeType()) { case BOOLEAN: return (T) Boolean.valueOf(jsonNode.asBoolean()); case NUMBER: if (jsonNode.isInt()) { return (T) Integer.valueOf(jsonNode.asInt()); } if (jsonNode.isDouble()) { return (T) Double.valueOf(jsonNode.asDouble()); } case STRING: return (T) jsonNode.asText(); default: throw new IllegalArgumentException(jsonNode.getNodeType() + " type is not yet supported"); } }
Example 6
Source File: DefaultHealthCheckUpdateHandler.java From armeria with Apache License 2.0 | 6 votes |
private static HealthCheckUpdateResult handlePut(AggregatedHttpRequest req) { final JsonNode json = toJsonNode(req); if (json.getNodeType() != JsonNodeType.OBJECT) { throw HttpStatusException.of(HttpStatus.BAD_REQUEST); } final JsonNode healthy = json.get("healthy"); if (healthy == null) { throw HttpStatusException.of(HttpStatus.BAD_REQUEST); } if (healthy.getNodeType() != JsonNodeType.BOOLEAN) { throw HttpStatusException.of(HttpStatus.BAD_REQUEST); } return healthy.booleanValue() ? HealthCheckUpdateResult.HEALTHY : HealthCheckUpdateResult.UNHEALTHY; }
Example 7
Source File: JsonObjectMapperDecoder.java From ffwd with Apache License 2.0 | 6 votes |
private Set<String> decodeTags(JsonNode tree, String name) { final JsonNode n = tree.get(name); if (n == null) { return EMPTY_TAGS; } if (n.getNodeType() != JsonNodeType.ARRAY) { return EMPTY_TAGS; } final List<String> tags = Lists.newArrayList(); final Iterator<JsonNode> iter = n.elements(); while (iter.hasNext()) { tags.add(iter.next().asText()); } return Sets.newHashSet(tags); }
Example 8
Source File: JSONReader.java From bigquery-etl-dataflow-sample with Apache License 2.0 | 6 votes |
/** * This method attempts to transform the json node into an object with a known type. * * @return an Object with the apparent type from JSON (number types are given their wide equivalent (Long for * ints, Double for float) */ private static Object nodeValueToObject(JsonNode node) { //No child objects or arrays in this flat data just text/number switch (node.getNodeType()) { case NUMBER: if (node.isFloat() || node.isDouble()) { return new Double(node.doubleValue()); } else { //For simplicity let all integers be Long. return new Long(node.asLong()); } case STRING: return node.asText(); case BOOLEAN: return node.asBoolean(); case NULL: return null; default: logger.warn("Unknown node type:" + node.getNodeType()); return null; } }
Example 9
Source File: ODataJsonDeserializer.java From olingo-odata4 with Apache License 2.0 | 5 votes |
private void checkJsonTypeBasedOnPrimitiveType(final String propertyName, final EdmPrimitiveType edmPrimitiveType, final JsonNode jsonNode) throws DeserializerException { boolean valid = true; if (edmPrimitiveType.getKind() == EdmTypeKind.DEFINITION) { checkJsonTypeBasedOnPrimitiveType(propertyName, ((EdmTypeDefinition) edmPrimitiveType).getUnderlyingType(), jsonNode); } else if (edmPrimitiveType.getKind() == EdmTypeKind.ENUM) { // Enum values must be strings. valid = jsonNode.isTextual(); } else { final String name = edmPrimitiveType.getName(); EdmPrimitiveTypeKind primKind; try { primKind = EdmPrimitiveTypeKind.valueOf(name); } catch (final IllegalArgumentException e) { throw new DeserializerException("Unknown Primitive Type: " + name, e, DeserializerException.MessageKeys.UNKNOWN_PRIMITIVE_TYPE, name, propertyName); } valid = matchTextualCase(jsonNode, primKind) || matchNumberCase(jsonNode, primKind) || matchBooleanCase(jsonNode, primKind) || matchIEEENumberCase(jsonNode, primKind) || jsonNode.isObject() && name.startsWith("Geo"); } if (!valid) { throw new DeserializerException( "Invalid json type: " + jsonNode.getNodeType() + " for " + edmPrimitiveType + " property: " + propertyName, DeserializerException.MessageKeys.INVALID_VALUE_FOR_PROPERTY, propertyName); } }
Example 10
Source File: JsonQueryObjectModelConverter.java From BIMserver with GNU Affero General Public License v3.0 | 5 votes |
private void parseProperties(QueryPart queryPart, ObjectNode properties) throws QueryException { Iterator<Entry<String, JsonNode>> fields = properties.fields(); while (fields.hasNext()) { Entry<String, JsonNode> entry = fields.next(); String propertySetName = entry.getKey(); JsonNode value = entry.getValue(); if (value.isObject()) { ObjectNode set = (ObjectNode)value; Iterator<Entry<String, JsonNode>> propertySetFields = set.fields(); while (propertySetFields.hasNext()) { Entry<String, JsonNode> propertyEntry = propertySetFields.next(); JsonNode propertyValue = propertyEntry.getValue(); if (propertyValue.isValueNode()) { if (propertyValue.getNodeType() == JsonNodeType.BOOLEAN) { queryPart.addProperty(propertySetName, propertyEntry.getKey(), propertyValue.asBoolean()); } else if (propertyValue.getNodeType() == JsonNodeType.NUMBER) { queryPart.addProperty(propertySetName, propertyEntry.getKey(), propertyValue.asDouble()); } else if (propertyValue.getNodeType() == JsonNodeType.STRING) { queryPart.addProperty(propertySetName, propertyEntry.getKey(), propertyValue.asText()); } else if (propertyValue.getNodeType() == JsonNodeType.NULL) { queryPart.addProperty(propertySetName, propertyEntry.getKey(), null); } } else { throw new QueryException("property \"" + propertyEntry.getKey() + "\" type not supported"); } } } else { throw new QueryException("Query language has changed, propertyset name required now"); } } }
Example 11
Source File: Utils.java From link-move with Apache License 2.0 | 5 votes |
private static boolean hasType(JsonNode node, JsonNodeType... types) { if (node == null) { return false; } for (JsonNodeType type : types) { if (node.getNodeType() == type) { return true; } } return false; }
Example 12
Source File: JsonCacheImpl.java From openapi-generator with Apache License 2.0 | 5 votes |
@Override public Object get(JsonPointer ptr) throws CacheException { Object result; if (root == null) { result = null; } else { try { JsonNode node = root.at(ptr); switch (node.getNodeType()) { case ARRAY: case OBJECT: result = node; break; case BINARY: result = node.binaryValue(); break; case BOOLEAN: result = node.booleanValue(); break; case NUMBER: result = node.numberValue(); break; case POJO: result = ((POJONode) node).getPojo(); break; case STRING: result = node.textValue(); break; default: result = null; break; } } catch (IOException e) { throw new CacheException(e); } } return result; }
Example 13
Source File: ExamplesTest.java From strimzi-kafka-operator with Apache License 2.0 | 5 votes |
private void validateTemplate(JsonNode rootNode) throws JsonProcessingException { JsonNode parameters = rootNode.get("parameters"); Map<String, Object> params = new HashMap<>(); for (JsonNode parameter : parameters) { String name = parameter.get("name").asText(); Object value; JsonNode valueNode = parameter.get("value"); switch (valueNode.getNodeType()) { case NULL: value = null; break; case NUMBER: case BOOLEAN: value = valueNode.toString(); break; case STRING: value = valueNode.asText(); break; default: throw new RuntimeException("Unsupported JSON type " + valueNode.getNodeType()); } params.put(name, value); } for (JsonNode object : rootNode.get("objects")) { String s = new YAMLMapper().enable(YAMLGenerator.Feature.MINIMIZE_QUOTES).enable(SerializationFeature.INDENT_OUTPUT).writeValueAsString(object); Matcher matcher = PARAMETER_PATTERN.matcher(s); StringBuilder sb = new StringBuilder(); int last = 0; while (matcher.find()) { sb.append(s, last, matcher.start()); String paramName = matcher.group(1); sb.append(params.get(paramName)); last = matcher.end(); } sb.append(s.substring(last)); String yamlContent = sb.toString(); validate(yamlContent); } }
Example 14
Source File: IsJsonObject.java From java-hamcrest with Apache License 2.0 | 5 votes |
private static Matcher<JsonNode> createNodeMatcher(final JsonNode value) { final JsonNodeType nodeType = value.getNodeType(); switch (nodeType) { case ARRAY: return IsJsonArray.jsonArray((ArrayNode) value); case BINARY: throw new UnsupportedOperationException( "Expected value contains a binary node, which is not implemented."); case BOOLEAN: return IsJsonBoolean.jsonBoolean((BooleanNode) value); case MISSING: return IsJsonMissing.jsonMissing((MissingNode) value); case NULL: return IsJsonNull.jsonNull((NullNode) value); case NUMBER: return IsJsonNumber.jsonNumber((NumericNode) value); case OBJECT: return IsJsonObject.jsonObject((ObjectNode) value); case POJO: throw new UnsupportedOperationException( "Expected value contains a POJO node, which is not implemented."); case STRING: return IsJsonText.jsonText((TextNode) value); default: throw new UnsupportedOperationException("Unsupported node type " + nodeType); } }
Example 15
Source File: DefaultPatchService.java From dhis2-core with BSD 3-Clause "New" or "Revised" License | 5 votes |
private List<Mutation> calculateMutations( String path, JsonNode node ) { List<Mutation> mutations = new ArrayList<>(); switch ( node.getNodeType() ) { case OBJECT: List<String> fieldNames = Lists.newArrayList( node.fieldNames() ); for ( String fieldName : fieldNames ) { mutations.addAll( calculateMutations( path + "." + fieldName, node.get( fieldName ) ) ); } break; case ARRAY: Collection<Object> identifiers = new ArrayList<>(); for ( JsonNode jsonNode : node ) { identifiers.add( getValue( jsonNode ) ); } mutations.add( new Mutation( path, identifiers ) ); break; default: mutations.add( new Mutation( path, getValue( node ) ) ); break; } return mutations; }
Example 16
Source File: Exclusion.java From batfish with Apache License 2.0 | 4 votes |
/** * Evaluates if the first object covers the second object. For it to be true, the two objects * should be of the same type and * * <p>i) If the type is atomic (e.g., string), should have equal values * * <p>ii) If the type is list, each element in the first object should cover some element in the * second. ['a'] covers ['a', 'b'] but not the other way around. * * <p>iii) If the type is map, each key in the first object should be present in the second object * and the corresponding first value should cover the second value. {'k1' : 'v1' } covers {'k1' : * 'v1', 'k2': 'v2'} but not the other way around. * * @param first The first object * @param second The second object * @return Results of the evaluation */ public static boolean firstCoversSecond(JsonNode first, JsonNode second) { if (first.isValueNode()) { return second.isValueNode() && first.equals(second); } else if (first.isArray()) { if (!second.isArray()) { return false; } for (JsonNode firstElement : first) { boolean covered = false; for (JsonNode secondElement : second) { if (firstCoversSecond(firstElement, secondElement)) { covered = true; break; } } if (!covered) { return false; } } // if we are here, all first elements must be covered return true; } else if (first.isObject()) { if (!second.isObject()) { return false; } Iterator<String> firstKeys = first.fieldNames(); while (firstKeys.hasNext()) { String key = firstKeys.next(); if (second.get(key) == null) { return false; } if (!firstCoversSecond(first.get(key), second.get(key))) { return false; } } // if we are here, all first keys must exist in second and first values cover second values return true; } else { throw new BatfishException("Missed some JsonNode type: " + first.getNodeType()); } }
Example 17
Source File: JsonFileReader.java From kafka-connect-fs with Apache License 2.0 | 4 votes |
private Object mapValue(Schema schema, JsonNode value) { if (value == null) return null; switch (value.getNodeType()) { case BOOLEAN: return value.booleanValue(); case NUMBER: if (value.isShort()) { return value.shortValue(); } else if (value.isInt()) { return value.intValue(); } else if (value.isLong()) { return value.longValue(); } else if (value.isFloat()) { return value.floatValue(); } else if (value.isDouble()) { return value.doubleValue(); } else if (value.isBigInteger()) { return value.bigIntegerValue(); } else { return value.numberValue(); } case STRING: return value.asText(); case BINARY: try { return value.binaryValue(); } catch (IOException ioe) { throw new RuntimeException(ioe); } case OBJECT: case POJO: Struct struct = new Struct(schema); Iterable<Map.Entry<String, JsonNode>> fields = value::fields; StreamSupport.stream(fields.spliterator(), false) .forEach(field -> struct.put(field.getKey(), mapValue(extractSchema(field.getValue()), field.getValue())) ); return struct; case ARRAY: Iterable<JsonNode> arrayElements = value::elements; return StreamSupport.stream(arrayElements.spliterator(), false) .map(elm -> mapValue(schema, elm)) .collect(Collectors.toList()); case NULL: case MISSING: default: return null; } }
Example 18
Source File: Jackson.java From centraldogma with Apache License 2.0 | 4 votes |
public static String textValue(JsonNode node, String defaultValue) { return node != null && node.getNodeType() == JsonNodeType.STRING ? node.textValue() : defaultValue; }
Example 19
Source File: CodeTransProcessor.java From vertx-codetrans with Apache License 2.0 | 4 votes |
@Override public synchronized void init(ProcessingEnvironment processingEnv) { super.init(processingEnv); String outputOption = processingEnv.getOptions().get("codetrans.output"); if (outputOption != null) { outputDir = new File(outputOption); } translator = new CodeTranslator(processingEnv); langs = new ArrayList<>(); String renderOpt = processingEnv.getOptions().get("codetrans.render"); renderMode = renderOpt != null ? RenderMode.valueOf(renderOpt.toUpperCase()) : RenderMode.EXAMPLE; String langsOpt = processingEnv.getOptions().get("codetrans.langs"); Set<String> langs; if (langsOpt != null) { langs = new HashSet<>(Arrays.asList(langsOpt.split("\\s*,\\s*"))); } else { langs = new HashSet<>(Arrays.asList("js", "ruby", "kotlin", "groovy")); } String configOpt = processingEnv.getOptions().get("codetrans.config"); if (configOpt != null) { ObjectMapper mapper = new ObjectMapper() .enable(JsonParser.Feature.ALLOW_COMMENTS) .enable(JsonParser.Feature.ALLOW_SINGLE_QUOTES); File file = new File(configOpt); try { config = (ObjectNode) mapper.readTree(file); } catch (IOException e) { System.err.println("[ERROR] Cannot read configuration file " + file.getAbsolutePath() + " : " + e.getMessage()); e.printStackTrace(); } } for (String lang : langs) { Lang l; switch (lang) { case "kotlin": l = new KotlinLang(); break; case "groovy": l = new GroovyLang(); break; case "scala": l = new ScalaLang(); break; default: continue; } this.langs.add(l); if (config != null) { JsonNode n = config.get(lang); if (n != null && n.getNodeType() == JsonNodeType.OBJECT) { JsonNode excludes = n.get("excludes"); if (excludes != null && excludes.getNodeType() == JsonNodeType.ARRAY) { Set<String> t = new HashSet<>(); abc.put(l.id(), t); for (int i = 0;i < excludes.size();i++) { JsonNode c = excludes.get(i); if (c.getNodeType() == JsonNodeType.STRING) { TextNode tn = (TextNode) c; t.add(tn.asText()); } } } } } } }
Example 20
Source File: JsonConvert.java From DBus with Apache License 2.0 | 4 votes |
private static Object convertToConnect(Schema schema, JsonNode jsonValue) { final Schema.Type schemaType; if (schema != null) { schemaType = schema.type(); if (jsonValue.isNull()) { if (schema.defaultValue() != null) return schema.defaultValue(); if (schema.isOptional()) return null; throw new DataException("Invalid null value for required " + schemaType + " field"); } } else { switch (jsonValue.getNodeType()) { case NULL: return null; case BOOLEAN: schemaType = Schema.Type.BOOLEAN; break; case NUMBER: if (jsonValue.isIntegralNumber()) schemaType = Schema.Type.INT64; else schemaType = Schema.Type.FLOAT64; break; case ARRAY: schemaType = Schema.Type.ARRAY; break; case OBJECT: schemaType = Schema.Type.MAP; break; case STRING: schemaType = Schema.Type.STRING; break; case BINARY: case MISSING: case POJO: default: schemaType = null; break; } } final JsonToTypeConverter typeConverter = TO_CONNECT_CONVERTERS.get(schemaType); if (typeConverter == null) throw new DataException("Unknown schema type: " + String.valueOf(schemaType)); Object converted = typeConverter.convert(schema, jsonValue); return converted; }