Java Json Create convertToJson(Object obj)

Here you can find the source of convertToJson(Object obj)

Description

Convert a nested Map data structure to a JSON String.

License

MIT License

Parameter

Parameter Description
obj The nested structure of maps.

Return

The JSON representation.

Declaration

public static String convertToJson(Object obj) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2012-2015 Bruno Ranschaert
 * Released under the MIT License: http://opensource.org/licenses/MIT
 * Library "jsonutil"//  www .ja  v  a  2 s.  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";

    /**
     * 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();
    }

    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();
    }
}

Related

  1. build(Map map)
  2. buildContentResponse(String userId, String message)
  3. buildJsonArray(String[][] twoDimensionArray)
  4. convertToJson(Object myObject)
  5. createArrayBuilder()
  6. createArrayBuilder()
  7. createJsonFrom(JsonObject user, String... ignoreKeys)
  8. createJsonValue(String string)