Wednesday, July 7, 2021

Traverse a Json using Jackson

import com.fasterxml.jackson.databind.JsonNode;

import com.fasterxml.jackson.databind.node.ObjectNode;

import org.apache.commons.lang3.StringUtils;


import java.util.Iterator;

import java.util.Map;

import java.util.Objects;


/**

 * @author: Bhupendra Singh@

 * @date 7/6/21 7:12 PM

 */

public class Traverse {

    /**

     * Traverse a Json using Jackson and also change the value of specific keys.

     *

     * @param jsonNode

     */

    public void traverse(final JsonNode jsonNode) {

        final Iterator<Map.Entry<String, JsonNode>> fieldsIterator = jsonNode.fields();

        while (fieldsIterator.hasNext()) {

            final Map.Entry<String, JsonNode> field = fieldsIterator.next();

            final String key = field.getKey();

            if (StringUtils.containsIgnoreCase(key, "KeyToBeChanged") && Objects.nonNull(

                field.getValue()) && !StringUtils.equalsIgnoreCase(field.getValue().toString(), "null")) {

                ((ObjectNode) jsonNode).put(key, "Value");

            }

            final JsonNode value = field.getValue();

            if (value.isContainerNode()) {

                traverse(value); // RECURSIVE CALL

            }

        }

    }


    /**

     * This method converts any json string to json node.

     *

     * @param jsonString

     * @return

     */

    public JsonNode toJsonNode(@NonNull final String jsonString) {

        try {

            return objectMapper.readTree(jsonString);

        } catch (final Exception e) {

            throw new RuntimeException("Failed to deserialize to JSONObject", e);

        }

    }

}


No comments:

Post a Comment

Add Your comments here...