List of usage examples for com.fasterxml.jackson.databind JsonNode getClass
@HotSpotIntrinsicCandidate public final native Class<?> getClass();
From source file:au.org.ands.vocabs.toolkit.db.TestJsonParsing.java
/** Main program. * @param args Command-line arguments./* w w w .j a v a 2 s . c o m*/ */ public static void main(final String[] args) { String jsonString = "[{\"type\": \"HARVEST\",\"provider_type\":" + " \"PoolParty\",\"project_id\":" + " \"1DCE1494-A022-0001-FFBD-12DE19E01FEB\"}," + "{\"type\": \"TRANSFORM\"},{\"type\": \"IMPORT\"}]"; JsonNode root = TaskUtils.jsonStringToTree(jsonString); if (root == null) { System.out.println("Got null."); } else { System.out.println("Got instance of:" + root.getClass().toString()); if (!(root instanceof ArrayNode)) { System.out.println("Didn't get an array."); } else { for (JsonNode node : (ArrayNode) root) { System.out.println("Got element: " + node.toString()); if (!(node instanceof ObjectNode)) { System.out.println("Didn't get an object."); } else { System.out.println("task type: " + node.get("type")); } } } } }
From source file:com.mapr.synth.samplers.ArrayFlattener.java
@Override public JsonNode sample() { JsonNode value = delegate.sample();/* w w w.j a v a 2s . c om*/ ArrayNode r = nodeFactory.arrayNode(); for (JsonNode component : value) { if (component.isArray()) { for (JsonNode node : component) { r.add(node); } } else { throw new IllegalArgumentException(String.format("Cannot flatten type %s", component.getClass())); } } return r; }
From source file:com.redhat.lightblue.util.JsonNodeCursor.java
@Override protected KeyValueCursor<String, JsonNode> getCursor(JsonNode node) { if (node instanceof ArrayNode) { return new ArrayElementCursor(((ArrayNode) node).elements()); } else if (node instanceof ObjectNode) { return new KeyValueCursorIteratorAdapter<>(((ObjectNode) node).fields()); } else {/* ww w.j a v a 2 s . co m*/ throw new IllegalArgumentException(node.getClass().getName()); } }
From source file:com.mapr.synth.samplers.FlattenSampler.java
@Override public JsonNode sample() { JsonNode value = delegate.sample();/*from www. ja v a2 s.com*/ if (value.isObject()) { ObjectNode r = new ObjectNode(nodeFactory); for (Iterator<String> it = value.fieldNames(); it.hasNext();) { String key = it.next(); JsonNode v = value.get(key); r.set(prefix + key, v); } return r; } else { ArrayNode r = nodeFactory.arrayNode(); for (JsonNode component : value) { if (component.isArray()) { for (JsonNode node : component) { r.add(node); } } else { throw new IllegalArgumentException( String.format("Cannot flatten type %s", component.getClass())); } } return r; } }
From source file:io.wcm.caravan.pipeline.impl.operators.MergeTransformer.java
@Override public Observable<JsonPipelineOutput> call(Observable<JsonPipelineOutput> primaryOutput) { return primaryOutput.zipWith(secondaryOutput, (primaryModel, secondaryModel) -> { log.debug("zipping object from secondary source into target property " + targetProperty); JsonNode jsonFromPrimary = primaryModel.getPayload(); JsonNode jsonFromSecondary = secondaryModel.getPayload(); if (!(jsonFromPrimary.isObject())) { throw new JsonPipelineOutputException( "Only pipelines with JSON *Objects* can be used as a target for a merge operation, but response data for " + primaryDescriptor + " contained " + jsonFromPrimary.getClass().getSimpleName()); }/* www . jav a 2s. c o m*/ // start with cloning the the response of the primary pipeline ObjectNode mergedObject = jsonFromPrimary.deepCopy(); // if a target property is specified, the JSON to be merged is inserted into this property if (isNotBlank(targetProperty)) { if (!mergedObject.has(targetProperty)) { // the target property does not exist yet, so we just can set the property mergedObject.set(targetProperty, jsonFromSecondary); } else { // the target property already exists - let's hope we can merge! JsonNode targetNode = mergedObject.get(targetProperty); if (!targetNode.isObject()) { throw new JsonPipelineOutputException( "When merging two pipelines into the same target property, both most contain JSON *Object* responses"); } if (!(jsonFromSecondary.isObject())) { throw new JsonPipelineOutputException( "Only pipelines with JSON *Object* responses can be merged into an existing target property"); } mergeAllPropertiesInto((ObjectNode) jsonFromSecondary, (ObjectNode) targetNode); } } else { // if no target property is specified, all properties of the secondary pipeline are copied into the merged object if (!(jsonFromSecondary.isObject())) { throw new JsonPipelineOutputException( "Only pipelines with JSON *Object* responses can be merged without specify a target property"); } mergeAllPropertiesInto((ObjectNode) jsonFromSecondary, mergedObject); } return primaryModel.withPayload(mergedObject) .withMaxAge(Math.min(primaryModel.getMaxAge(), secondaryModel.getMaxAge())); }); }
From source file:com.palominolabs.testutil.JsonAssert.java
private static void assertJsonNodeEquals(String msg, JsonNode expected, JsonNode actual) { if (expected.isTextual()) { if (actual.isTextual()) { assertEquals(msg, expected.textValue(), actual.textValue()); } else {/* w w w.j a va2s . c om*/ nonMatchingClasses(msg, expected, actual); } } else if (expected.isInt()) { if (actual.isInt()) { assertEquals(msg, expected.intValue(), actual.intValue()); } else { nonMatchingClasses(msg, expected, actual); } } else if (expected.isObject()) { if (actual.isObject()) { assertJsonObjectEquals(msg, (ObjectNode) expected, (ObjectNode) actual); } else { nonMatchingClasses(msg, expected, actual); } } else if (expected.isArray()) { if (actual.isArray()) { assertJsonArrayEquals(msg, (ArrayNode) expected, (ArrayNode) actual); } else { nonMatchingClasses(msg, expected, actual); } } else if (expected == NullNode.getInstance()) { if (actual == NullNode.getInstance()) { return; } nonMatchingClasses(msg, expected, actual); } else if (expected.isBoolean()) { if (actual.isBoolean()) { assertEquals(msg, expected.booleanValue(), actual.booleanValue()); } else { nonMatchingClasses(msg, expected, actual); } } else { fail(msg + "/Can only handle recursive Object, Array and Null instances, got a " + expected.getClass() + ": " + expected); } }
From source file:com.github.pjungermann.config.types.json.JsonConverter.java
@Nullable protected Object extractValue(@NotNull final JsonNode node) { if (node.isNull()) { return null; }/*w w w.j ava 2 s . c o m*/ if (node.isBoolean()) { return node.booleanValue(); } if (node.isNumber()) { return node.numberValue(); } if (node.isTextual()) { return node.textValue(); } if (node.isBinary()) { try { return node.binaryValue(); } catch (IOException e) { LOGGER.error( String.format("failed to read binary value from node %s of type %s", node, node.getClass()), e); } } if (node instanceof ArrayNode) { return prepareEntries((ArrayNode) node); } throw new UnsupportedOperationException( String.format("node %s of type %s is not supported", node, node.getClass())); }
From source file:io.apiman.test.common.json.JsonCompare.java
/** * Asserts that the JSON document matches what we expected. * @param expectedJson//ww w .ja va 2 s.c o m * @param actualJson */ public void assertJson(JsonNode expectedJson, JsonNode actualJson) { if (expectedJson instanceof ArrayNode) { JsonNode actualValue = actualJson; ArrayNode expectedArray = (ArrayNode) expectedJson; Assert.assertEquals( message("Expected JSON array but found non-array [{0}] instead.", actualValue.getClass().getSimpleName()), expectedJson.getClass(), actualValue.getClass()); ArrayNode actualArray = (ArrayNode) actualValue; Assert.assertEquals(message("Array size mismatch."), expectedArray.size(), actualArray.size()); JsonNode[] expected = new JsonNode[expectedArray.size()]; JsonNode[] actual = new JsonNode[actualArray.size()]; for (int idx = 0; idx < expected.length; idx++) { expected[idx] = expectedArray.get(idx); actual[idx] = actualArray.get(idx); } // If strict ordering is disabled, then sort both arrays if (getArrayOrdering() == JsonArrayOrderingType.any) { Comparator<? super JsonNode> comparator = new Comparator<JsonNode>() { @Override public int compare(JsonNode o1, JsonNode o2) { String str1 = o1.asText(); String str2 = o2.asText(); if (o1.isObject() && o2.isObject()) { // Try name (PermissionBean only) JsonNode o1NameNode = o1.get("name"); JsonNode o2NameNode = o2.get("name"); if (o1NameNode != null && o2NameNode != null) { str1 = o1NameNode.asText(); str2 = o2NameNode.asText(); } // Try username (UserBean only) JsonNode o1UsernameNode = o1.get("username"); JsonNode o2UsernameNode = o2.get("username"); if (o1UsernameNode != null && o2UsernameNode != null) { str1 = o1UsernameNode.asText(); str2 = o2UsernameNode.asText(); } // Try version (*VersionBeans) JsonNode o1VersionNode = o1.get("version"); JsonNode o2VersionNode = o2.get("version"); if (o1VersionNode != null && o2VersionNode != null) { str1 = o1VersionNode.asText(); str2 = o2VersionNode.asText(); } // Try OrganizationBean.id (Orgs) JsonNode o1OrgNode = o1.get("OrganizationBean"); JsonNode o2OrgNode = o2.get("OrganizationBean"); if (o1OrgNode != null && o2OrgNode != null) { str1 = o1OrgNode.get("id").asText(); str2 = o2OrgNode.get("id").asText(); } // Try ClientBean.id (Orgs) JsonNode o1ClientNode = o1.get("ClientBean"); JsonNode o2ClientNode = o2.get("ClientBean"); if (o1ClientNode != null && o2ClientNode != null) { str1 = o1ClientNode.get("id").asText(); str2 = o2ClientNode.get("id").asText(); } // Try PlanBean.id (Orgs) JsonNode o1PlanNode = o1.get("PlanBean"); JsonNode o2PlanNode = o2.get("PlanBean"); if (o1PlanNode != null && o2PlanNode != null) { str1 = o1PlanNode.get("id").asText(); str2 = o2PlanNode.get("id").asText(); } // Try ApiBean.id (Orgs) JsonNode o1ApiNode = o1.get("ApiBean"); JsonNode o2ApiNode = o2.get("ApiBean"); if (o1ApiNode != null && o2ApiNode != null) { str1 = o1ApiNode.get("id").asText(); str2 = o2ApiNode.get("id").asText(); } // Try Id (all other beans) JsonNode o1IdNode = o1.get("id"); JsonNode o2IdNode = o2.get("id"); if (o1IdNode != null && o2IdNode != null) { if (o1IdNode.isNumber()) { return new Long(o1IdNode.asLong()).compareTo(o2IdNode.asLong()); } str1 = o1IdNode.asText(); str2 = o2IdNode.asText(); } } int cmp = str1.compareTo(str2); if (cmp == 0) cmp = 1; return cmp; } }; Arrays.sort(expected, comparator); Arrays.sort(actual, comparator); } for (int idx = 0; idx < expected.length; idx++) { currentPath.push(idx); assertJson(expected[idx], actual[idx]); currentPath.pop(); } } else { Iterator<Entry<String, JsonNode>> fields = expectedJson.fields(); Set<String> expectedFieldNames = new HashSet<>(); while (fields.hasNext()) { Entry<String, JsonNode> entry = fields.next(); String expectedFieldName = entry.getKey(); expectedFieldNames.add(expectedFieldName); JsonNode expectedValue = entry.getValue(); currentPath.push(expectedFieldName); if (expectedValue instanceof TextNode) { TextNode tn = (TextNode) expectedValue; String expected = tn.textValue(); JsonNode actualValue = actualJson.get(expectedFieldName); if (isIgnoreCase()) { expected = expected.toLowerCase(); if (actualValue == null) { actualValue = actualJson.get(expectedFieldName.toLowerCase()); } } Assert.assertNotNull( message("Expected JSON text field \"{0}\" with value \"{1}\" but was not found.", expectedFieldName, expected), actualValue); Assert.assertEquals(message( "Expected JSON text field \"{0}\" with value \"{1}\" but found non-text [{2}] field with that name instead.", expectedFieldName, expected, actualValue.getClass().getSimpleName()), TextNode.class, actualValue.getClass()); String actual = ((TextNode) actualValue).textValue(); if (isIgnoreCase()) { if (actual != null) { actual = actual.toLowerCase(); } } if (!expected.equals("*")) { Assert.assertEquals(message("Value mismatch for text field \"{0}\".", expectedFieldName), expected, actual); } } else if (expectedValue.isNumber()) { NumericNode numeric = (NumericNode) expectedValue; Number expected = numeric.numberValue(); JsonNode actualValue = actualJson.get(expectedFieldName); try { Assert.assertNotNull( message("Expected JSON numeric field \"{0}\" with value \"{1}\" but was not found.", expectedFieldName, expected), actualValue); } catch (Error e) { throw e; } Assert.assertTrue(message( "Expected JSON numeric field \"{0}\" with value \"{1}\" but found non-numeric [{2}] field with that name instead.", expectedFieldName, expected, actualValue.getClass().getSimpleName()), actualValue.isNumber()); Number actual = ((NumericNode) actualValue).numberValue(); if (!"id".equals(expectedFieldName) || isCompareNumericIds()) { Assert.assertEquals(message("Value mismatch for numeric field \"{0}\".", expectedFieldName), expected, actual); } } else if (expectedValue instanceof BooleanNode) { BooleanNode bool = (BooleanNode) expectedValue; Boolean expected = bool.booleanValue(); JsonNode actualValue = actualJson.get(expectedFieldName); Assert.assertNotNull( message("Expected JSON boolean field \"{0}\" with value \"{1}\" but was not found.", expectedFieldName, expected), actualValue); Assert.assertEquals(message( "Expected JSON boolean field \"{0}\" with value \"{1}\" but found non-boolean [{2}] field with that name instead.", expectedFieldName, expected, actualValue.getClass().getSimpleName()), expectedValue.getClass(), actualValue.getClass()); Boolean actual = ((BooleanNode) actualValue).booleanValue(); Assert.assertEquals(message("Value mismatch for boolean field \"{0}\".", expectedFieldName), expected, actual); } else if (expectedValue instanceof ObjectNode) { JsonNode actualValue = actualJson.get(expectedFieldName); Assert.assertNotNull( message("Expected parent JSON field \"{0}\" but was not found.", expectedFieldName), actualValue); Assert.assertEquals( message("Expected parent JSON field \"{0}\" but found field of type \"{1}\".", expectedFieldName, actualValue.getClass().getSimpleName()), ObjectNode.class, actualValue.getClass()); assertJson(expectedValue, actualValue); } else if (expectedValue instanceof ArrayNode) { JsonNode actualValue = actualJson.get(expectedFieldName); Assert.assertNotNull( message("Expected JSON array field \"{0}\" but was not found.", expectedFieldName), actualValue); ArrayNode expectedArray = (ArrayNode) expectedValue; Assert.assertEquals(message( "Expected JSON array field \"{0}\" but found non-array [{1}] field with that name instead.", expectedFieldName, actualValue.getClass().getSimpleName()), expectedValue.getClass(), actualValue.getClass()); ArrayNode actualArray = (ArrayNode) actualValue; Assert.assertEquals(message("Field \"{0}\" array size mismatch.", expectedFieldName), expectedArray.size(), actualArray.size()); assertJson(expectedArray, actualArray); } else if (expectedValue instanceof NullNode) { JsonNode actualValue = actualJson.get(expectedFieldName); Assert.assertNotNull( message("Expected Null JSON field \"{0}\" but was not found.", expectedFieldName), actualValue); Assert.assertEquals( message("Expected Null JSON field \"{0}\" but found field of type \"{0}\".", expectedFieldName, actualValue.getClass().getSimpleName()), NullNode.class, actualValue.getClass()); } else { Assert.fail(message("Unsupported field type: {0}", expectedValue.getClass().getSimpleName())); } currentPath.pop(); } if (getMissingField() == JsonMissingFieldType.fail) { Set<String> actualFieldNames = new HashSet(); Iterator<String> names = actualJson.fieldNames(); while (names.hasNext()) { actualFieldNames.add(names.next()); } actualFieldNames.removeAll(expectedFieldNames); Assert.assertTrue(message("Found unexpected fields: {0}", StringUtils.join(actualFieldNames, ", ")), actualFieldNames.isEmpty()); } } }
From source file:org.apache.drill.exec.ref.rse.JSONRecordReader.java
private DataValue convert(JsonNode node) { if (node == null || node.isNull() || node.isMissingNode()) { return DataValue.NULL_VALUE; } else if (node.isArray()) { SimpleArrayValue arr = new SimpleArrayValue(node.size()); for (int i = 0; i < node.size(); i++) { arr.addToArray(i, convert(node.get(i))); }//from w ww. j ava 2 s .c om return arr; } else if (node.isObject()) { SimpleMapValue map = new SimpleMapValue(); String name; for (Iterator<String> iter = node.fieldNames(); iter.hasNext();) { name = iter.next(); map.setByName(name, convert(node.get(name))); } return map; } else if (node.isBinary()) { try { return new BytesScalar(node.binaryValue()); } catch (IOException e) { throw new RuntimeException("Failure converting binary value.", e); } } else if (node.isBigDecimal()) { throw new UnsupportedOperationException(); // return new BigDecimalScalar(node.decimalValue()); } else if (node.isBigInteger()) { throw new UnsupportedOperationException(); // return new BigIntegerScalar(node.bigIntegerValue()); } else if (node.isBoolean()) { return new BooleanScalar(node.asBoolean()); } else if (node.isFloatingPointNumber()) { if (node.isBigDecimal()) { throw new UnsupportedOperationException(); // return new BigDecimalScalar(node.decimalValue()); } else { return new DoubleScalar(node.asDouble()); } } else if (node.isInt()) { return new IntegerScalar(node.asInt()); } else if (node.isLong()) { return new LongScalar(node.asLong()); } else if (node.isTextual()) { return new StringScalar(node.asText()); } else { throw new UnsupportedOperationException(String.format("Don't know how to convert value of type %s.", node.getClass().getCanonicalName())); } }
From source file:org.commonwl.view.cwl.CWLService.java
/** * Get the steps for a particular document * @param cwlDoc The document to get steps for * @return A map of step IDs and details related to them *//* ww w. ja v a 2s . c o m*/ private Map<String, CWLStep> getSteps(JsonNode cwlDoc) { if (cwlDoc != null && cwlDoc.has(STEPS)) { Map<String, CWLStep> returnMap = new HashMap<>(); JsonNode steps = cwlDoc.get(STEPS); if (steps.getClass() == ArrayNode.class) { // Explicit ID and other fields within each input list for (JsonNode step : steps) { CWLStep stepObject = new CWLStep(extractLabel(step), extractDoc(step), extractRun(step), getInputs(step)); returnMap.put(extractID(step), stepObject); } } else if (steps.getClass() == ObjectNode.class) { // ID is the key of each object Iterator<Map.Entry<String, JsonNode>> iterator = steps.fields(); while (iterator.hasNext()) { Map.Entry<String, JsonNode> stepNode = iterator.next(); JsonNode stepJson = stepNode.getValue(); CWLStep stepObject = new CWLStep(extractLabel(stepJson), extractDoc(stepJson), extractRun(stepJson), getInputs(stepJson)); returnMap.put(stepNode.getKey(), stepObject); } } return returnMap; } return null; }