Java Map to Json toJSON(Map map)

Here you can find the source of toJSON(Map map)

Description

Builds a JSON string form the given map

License

Educational Community License

Parameter

Parameter Description
map map to translate

Return

String in JSON format

Declaration

public static String toJSON(Map<String, String> map) 

Method Source Code

//package com.java2s;
/**//  w w  w .  ja  v a2  s  .c  o m
 * Copyright 2005-2015 The Kuali Foundation
 *
 * Licensed under the Educational Community License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.opensource.org/licenses/ecl2.php
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.util.Map;

public class Main {
    /**
     * Builds a JSON string form the given map
     * 
     * @param map map to translate
     * @return String in JSON format
     */
    public static String toJSON(Map<String, String> map) {
        StringBuffer sb = new StringBuffer("{");

        for (String key : map.keySet()) {
            String optionValue = map.get(key);
            if (sb.length() > 1) {
                sb.append(",");
            }
            sb.append("\"" + key + "\"");

            sb.append(":");
            sb.append("\"" + escapeJSONString(optionValue) + "\"");
        }
        sb.append("}");

        return sb.toString();
    }

    /**
     * Escapes double quotes present in the given string
     * 
     * @param jsonString string to escape
     * @return escaped string
     */
    public static String escapeJSONString(String jsonString) {
        if (jsonString != null) {
            jsonString = jsonString.replace("\"", "&quot;");
        }

        return jsonString;
    }
}

Related

  1. mapToJson(Map parameters)
  2. mapToJson(Map map)
  3. toJson(Map map)
  4. toJSON(Map map)
  5. toJSON(Map map)
  6. toJSONString(Map map, int indentLevel)