private static <T> T toValue(ObjectCodec codec, JsonNode node, Class<T> valueType) throws JsonProcessingException { if (node.isPojo()) { Object pojo = ((POJONode) node).getPojo(); if (valueType.isInstance(pojo)) { return valueType.cast(pojo); } } return codec.treeToValue(node, valueType); }
public void testEmbeddedObjectInArray() throws Exception { TokenBuffer buf = new TokenBuffer(MAPPER); buf.writeStartArray(); buf.writeObject(MARKER); buf.writeEndArray(); JsonNode node = MAPPER.readTree(buf.asParser()); buf.close(); assertTrue(node.isArray()); assertEquals(1, node.size()); JsonNode n = node.get(0); assertTrue(n.isPojo()); assertSame(MARKER, ((POJONode) n).getPojo()); }
/** * Determines whether or not the given {@link JsonNode} matches the given type. This method is * limitted to a few java types only and shouldn't be used to determine with great accuracy * whether or not the types match. * * @param node the {@link JsonNode} * @param type the {@link Class} * @return true if the types match, false otherwise */ protected boolean isMatchingType(JsonNode node, Class<?> type) { if (node.isNull()) { return true; } else if (node.isTextual()) { return String.class.isAssignableFrom(type); } else if (node.isNumber()) { return Number.class.isAssignableFrom(type) || short.class.isAssignableFrom(type) || int.class.isAssignableFrom(type) || long.class.isAssignableFrom(type) || float.class.isAssignableFrom(type) || double.class.isAssignableFrom(type); } else if (node.isArray() && type.isArray()) { return (node.size() > 0) ? isMatchingType(node.get(0), type.getComponentType()) : false; } else if (node.isArray()) { return type.isArray() || Collection.class.isAssignableFrom(type); } else if (node.isBinary()) { return byte[].class.isAssignableFrom(type) || Byte[].class.isAssignableFrom(type) || char[].class.isAssignableFrom(type) || Character[].class.isAssignableFrom(type); } else if (node.isBoolean()) { return boolean.class.isAssignableFrom(type) || Boolean.class.isAssignableFrom(type); } else if (node.isObject() || node.isPojo()) { return !type.isPrimitive() && !String.class.isAssignableFrom(type) && !Number.class.isAssignableFrom(type) && !Boolean.class.isAssignableFrom(type); } // not sure if it's a matching type return false; }