Example usage for com.fasterxml.jackson.core TreeNode isObject

List of usage examples for com.fasterxml.jackson.core TreeNode isObject

Introduction

In this page you can find the example usage for com.fasterxml.jackson.core TreeNode isObject.

Prototype

boolean isObject();

Source Link

Document

Method that returns true if this node is an Object node, false otherwise.

Usage

From source file:eu.trentorise.opendata.commons.test.jackson.OdtJacksonTester.java

/**
* Converts {@code obj} to an {@link ObjectNode}, sets field
* {@code fieldName} to {@code newNode} and returns the json string
* representation of such new object. Also logs the json with the provided logger at FINE
* level./*from  w  w w . ja  va2  s  .c o  m*/
*/
public static String changeField(ObjectMapper objectMapper, Logger logger, Object obj, String fieldName,
        JsonNode newNode) {
    checkNotNull(obj);
    checkNotEmpty(fieldName, "Invalid field name!");

    String string;
    try {
        string = objectMapper.writeValueAsString(obj);
    } catch (JsonProcessingException ex) {
        throw new RuntimeException("Error while jacksonizing object to json node!", ex);
    }
    TreeNode treeNode;
    try {
        treeNode = (ObjectNode) objectMapper.readTree(string);
    } catch (IOException ex) {
        throw new RuntimeException("Error while creating json tree from serialized object:" + string, ex);
    }
    if (!treeNode.isObject()) {
        throw new OdtException(
                "The provided object was jacksonized to a string which does not represent a JSON object! String is "
                        + string);
    }
    ObjectNode jo = (ObjectNode) treeNode;
    jo.put(fieldName, newNode);

    String json = jo.toString();

    logger.log(Level.FINE, "converted json = {0}", json);

    return json;

}

From source file:eu.trentorise.opendata.commons.test.jackson.TodJacksonTester.java

/**
 * Converts {@code obj} to an {@link ObjectNode}, sets field
 * {@code fieldName} to {@code newNode} and returns the json string
 * representation of such new object. Also logs the json with the provided
 * logger at FINE level./*from w w  w  . j  ava  2 s.c  o  m*/
 */
public static String changeField(ObjectMapper objectMapper, Logger logger, Object obj, String fieldName,
        JsonNode newNode) {
    checkNotNull(obj);
    checkNotEmpty(fieldName, "Invalid field name!");

    String string;
    try {
        string = objectMapper.writeValueAsString(obj);
    } catch (JsonProcessingException ex) {
        throw new RuntimeException("Error while jacksonizing object to json node!", ex);
    }
    TreeNode treeNode;
    try {
        treeNode = (ObjectNode) objectMapper.readTree(string);
    } catch (IOException ex) {
        throw new RuntimeException("Error while creating json tree from serialized object:" + string, ex);
    }
    if (!treeNode.isObject()) {
        throw new TodException(
                "The provided object was jacksonized to a string which does not represent a JSON object! String is "
                        + string);
    }
    ObjectNode jo = (ObjectNode) treeNode;
    jo.put(fieldName, newNode);

    String json = jo.toString();

    logger.log(Level.FINE, "converted json = {0}", json);

    return json;

}

From source file:io.coala.json.DynaBean.java

/**
 * @param referenceType//  w  ww  .  jav  a2 s.  c om
 * @param <S>
 * @param <T>
 * @return
 */
static final <S, T> JsonDeserializer<T> createJsonDeserializer(final ObjectMapper om, final Class<T> resultType,
        final Properties... imports) {
    return new JsonDeserializer<T>() {

        @Override
        public T deserializeWithType(final JsonParser jp, final DeserializationContext ctxt,
                final TypeDeserializer typeDeserializer) throws IOException, JsonProcessingException {
            return deserialize(jp, ctxt);
        }

        @Override
        public T deserialize(final JsonParser jp, final DeserializationContext ctxt)
                throws IOException, JsonProcessingException {
            if (jp.getCurrentToken() == JsonToken.VALUE_NULL)
                return null;

            //            if( Wrapper.class.isAssignableFrom( resultType ) )
            //            {
            //               // FIXME
            //               LOG.trace( "deser wrapper intf of {}", jp.getText() );
            //               return (T) Wrapper.Util.valueOf( jp.getText(),
            //                     resultType.asSubclass( Wrapper.class ) );
            //            } 
            if (Config.class.isAssignableFrom(resultType)) {
                final Map<String, Object> entries = jp.readValueAs(new TypeReference<Map<String, Object>>() {
                });

                final Iterator<Entry<String, Object>> it = entries.entrySet().iterator();
                for (Entry<String, Object> next = null; it.hasNext(); next = it.next())
                    if (next != null && next.getValue() == null) {
                        LOG.trace("Ignoring null value: {}", next);
                        it.remove();
                    }
                return resultType.cast(ConfigFactory.create(resultType.asSubclass(Config.class), entries));
            }
            // else if (Config.class.isAssignableFrom(resultType))
            // throw new JsonGenerationException(
            // "Config does not extend "+Mutable.class.getName()+" required for deserialization: "
            // + Arrays.asList(resultType
            // .getInterfaces()));

            // can't parse directly to interface type
            final DynaBean bean = new DynaBean();
            final TreeNode tree = jp.readValueAsTree();

            // override attributes as defined in interface getters
            final Set<String> attributes = new HashSet<>();
            for (Method method : resultType.getMethods()) {
                if (method.getReturnType().equals(Void.TYPE) || method.getParameterTypes().length != 0)
                    continue;

                final String attribute = method.getName();
                if (attribute.equals("toString") || attribute.equals("hashCode"))
                    continue;

                attributes.add(attribute);
                final TreeNode value = tree.get(attribute);// bean.any().get(attributeName);
                if (value == null)
                    continue;

                bean.set(method.getName(),
                        om.treeToValue(value, JsonUtil.checkRegistered(om, method.getReturnType(), imports)));
            }
            if (tree.isObject()) {
                // keep superfluous properties as TreeNodes, just in case
                final Iterator<String> fieldNames = tree.fieldNames();
                while (fieldNames.hasNext()) {
                    final String fieldName = fieldNames.next();
                    if (!attributes.contains(fieldName))
                        bean.set(fieldName, tree.get(fieldName));
                }
            } else if (tree.isValueNode()) {
                for (Class<?> type : resultType.getInterfaces())
                    for (Method method : type.getDeclaredMethods()) {
                        //                     LOG.trace( "Scanning {}", method );
                        if (method.isAnnotationPresent(JsonProperty.class)) {
                            final String property = method.getAnnotation(JsonProperty.class).value();
                            //                        LOG.trace( "Setting {}: {}", property,
                            //                              ((ValueNode) tree).textValue() );
                            bean.set(property, ((ValueNode) tree).textValue());
                        }
                    }
            } else
                throw ExceptionFactory.createUnchecked("Expected {} but parsed: {}", resultType,
                        tree.getClass());

            return DynaBean.proxyOf(om, resultType, bean, imports);
        }
    };
}