Pass in a Map and this method will return a JSON string. - Java JSON

Java examples for JSON:JSON String

Description

Pass in a Map and this method will return a JSON string.

Demo Code


import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Main{
    private static Logger logger = Logger.getLogger(JSONUtility.class
            .getName());/*  w ww  . j  a v a  2 s.c  om*/
    /**
     * Pass in a Map and this method will return a JSON string.
     * <p>
     * The map can contain Objects, int[], Object[] and Collections and they will be converted into string representations.
     * <p>
     * Nested maps can be included as values and the JSON will have nested object notation.
     * <p>
     * Arrays/Collections can have Maps in them as well.
     * <p>
     * See the unit tests for examples.
     * 
     * @param jsonData
     * @return
     */
    public static String jsonFromMap(Map<String, Object> jsonData) {
        try {
            JsonDocument json = new JsonDocument();
            json.startGroup();

            for (String key : jsonData.keySet()) {
                Object data = jsonData.get(key);
                if (data instanceof Map) {
                    /* it's a nested map, so we'll recursively add the JSON of this map to the current JSON */
                    json.addValue(key,
                            jsonFromMap((Map<String, Object>) data));
                } else if (data instanceof Object[]) {
                    /* it's an object array, so we'll iterate the elements and put them all in here */
                    json.addValue(key, "["
                            + stringArrayFromObjectArray((Object[]) data)
                            + "]");
                } else if (data instanceof Collection) {
                    /* it's a collection, so we'll iterate the elements and put them all in here */
                    json.addValue(
                            key,
                            "["
                                    + stringArrayFromObjectArray(((Collection) data)
                                            .toArray()) + "]");
                } else if (data instanceof int[]) {
                    /* it's an int array, so we'll get the string representation */
                    String intArray = Arrays.toString((int[]) data);
                    /* remove whitespace */
                    intArray = intArray.replaceAll(" ", "");
                    json.addValue(key, intArray);
                } else if (data instanceof JSONCapableObject) {
                    json.addValue(key,
                            jsonFromMap(((JSONCapableObject) data)
                                    .jsonMap()));
                } else {
                    /* all other objects we assume we are to just put the string value in */
                    json.addValue(key, String.valueOf(data));
                }
            }

            json.endGroup();

            logger.log(Level.FINER,
                    "created json from map => " + json.toString());
            return json.toString();
        } catch (Exception e) {
            logger.log(Level.SEVERE, "Could not create JSON from Map. ", e);
            return "{}";
        }

    }
    private static String stringArrayFromObjectArray(Object[] data) {
        StringBuilder arrayAsString = new StringBuilder();
        for (Object o : data) {
            if (arrayAsString.length() > 0) {
                arrayAsString.append(",");
            }
            if (o instanceof Map) {
                arrayAsString.append(jsonFromMap((Map<String, Object>) o));
            } else if (o instanceof JSONCapableObject) {
                arrayAsString.append(jsonFromMap(((JSONCapableObject) o)
                        .jsonMap()));
            } else {
                arrayAsString.append("\"").append(String.valueOf(o))
                        .append("\"");
            }
        }
        return arrayAsString.toString();
    }
}

Related Tutorials