Java Map to Json mapToJson(Map map, boolean pretty, String indent)

Here you can find the source of mapToJson(Map map, boolean pretty, String indent)

Description

map To Json

License

MIT License

Declaration

private static String mapToJson(Map<String, Object> map, boolean pretty, String indent) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2012-2015 Bruno Ranschaert
 * Released under the MIT License: http://opensource.org/licenses/MIT
 * Library "jsonutil"/*from w  w w .  j  a v a  2s.co m*/
 ******************************************************************************/

import java.util.*;
import java.util.Map.Entry;

public class Main {
    private static final String INDENT = "  ";
    private static final String NULL_LITERAL = "null";

    private static String mapToJson(Map<String, Object> map, boolean pretty, String indent) {
        StringBuilder builder = new StringBuilder(1024);
        builder.append(pretty ? indent + "{\n" : "{");
        int count = 0;
        for (Entry<String, Object> entry : map.entrySet()) {
            //
            final String key = entry.getKey();
            final Object val = entry.getValue();
            //
            if (count > 0) {
                builder.append(pretty ? ",\n" : ",");
            }
            count++;
            builder.append(pretty ? indent + INDENT : "");
            builder.append("\"");
            builder.append(key);
            builder.append("\"");
            builder.append(":");

            String value = convertToJson(val, pretty, indent + INDENT + INDENT);
            if (pretty) {
                // Remove indents for simple values ...
                String trimmedValue = value.trim();
                if (!trimmedValue.startsWith("{") && !trimmedValue.startsWith("[")) {
                    value = trimmedValue;
                } else {
                    builder.append("\n");
                }
            }
            builder.append(value);
        }
        builder.append(pretty ? "\n" + indent + "}" : "}");
        return builder.toString();
    }

    /**
     * Convert a nested Map data structure to a JSON String. Nested maps, lists
     * and key/values are supported. We will not try to convert
     * beans/properties, it will not work on ordinary beans. General instances
     * will be converted to quoted String values.
     * 
     * @param obj
     *            The nested structure of maps.
     * 
     * @return The JSON representation.
     */
    public static String convertToJson(Object obj) {
        return convertToJson(obj, false);
    }

    /**
     * Convert a nested Map data structure to a JSON String. Nested maps, lists
     * and key/values are supported. We will not try to convert
     * beans/properties, it will not work on ordinary beans. General instances
     * will be converted to quoted String values.
     * 
     * @param obj
     *            The nested structure of maps.
     * @param pretty
     *            Pretty print flag.
     * 
     * @return The JSON representation.
     */
    public static String convertToJson(Object obj, boolean pretty) {
        return convertToJson(obj, pretty, "");
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    private static String convertToJson(Object obj, boolean pretty, String indent) {
        if (obj == null) {
            // 'null' is a valid JSON literal.
            //
            return NULL_LITERAL;
        } else if (obj instanceof Collection) {
            //
            return collToJson((Collection) obj, pretty, indent);
            //
        } else if (obj instanceof Map) {
            //
            return mapToJson((Map<String, Object>) obj, pretty, indent);
        } else if (obj instanceof Number) {
            // No quotes for numbers.
            //
            return (pretty ? indent : "") + obj.toString();
        } else if (obj instanceof Boolean) {
            // No quotes for booleans.
            return (pretty ? indent : "") + obj.toString();
        } else {
            // Strings should be quoted.
            return (pretty ? indent : "") + "\"" + obj.toString().replace("\"", "'") + "\"";
        }
    }

    private static String collToJson(Collection<?> coll, boolean pretty, String indent) {
        StringBuilder builder = new StringBuilder(1024);
        builder.append(pretty ? indent + "[\n" : "[");
        int count = 0;
        for (Object el : coll) {
            if (count > 0) {
                builder.append(pretty ? ",\n" : ",");
            }
            count++;
            builder.append(convertToJson(el, pretty, indent + INDENT));
        }
        builder.append(pretty ? "\n" + indent + "]" : "]");
        return builder.toString();
    }
}

Related

  1. mapToJson(Map map)
  2. mapToJson(Map parameters)
  3. mapToJson(Map map)
  4. toJson(Map map)
  5. toJSON(Map map)