Java Json Create toJsonString(Map map)

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

Description

to Json String

License

Apache License

Declaration

public static String toJsonString(Map map) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Map;
import java.util.Map.Entry;

public class Main {
    static SimpleDateFormat DF = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");

    public static String toJsonString(Map map) {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        for (Object entryO : map.entrySet()) {
            if (sb.length() > 1) {
                sb.append(",");
            }//from w ww  .  j a v  a2s.  c  om
            Entry entry = (Entry) entryO;
            sb.append("\"");
            sb.append(entry.getKey());
            sb.append("\":");

            Object value = entry.getValue();
            sb.append(toJsonString(value));
        }
        sb.append("}");
        return sb.toString();
    }

    public static String toJsonString(Collection col) {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        for (Object e : col) {
            if (sb.length() > 1) {
                sb.append(",");
            }
            sb.append(toJsonString(e));
        }
        sb.append("]");
        return sb.toString();
    }

    public static String toJsonString(Object value) {
        if (value instanceof String) {
            return "\"" + String.valueOf(value).replaceAll("\\\\", "\\\\\\\\").replaceAll("\"", "\\\\\"")
                    .replaceAll("\t", " ").replaceAll("\r?\n", "\\\\n") + "\"";
        } else if (value instanceof Date) {
            return "\"" + DF.format((Date) value) + "\"";
            // 2014-08-14T11:22:31
        } else if (value instanceof Map) {
            return toJsonString((Map) value);
        } else if (value instanceof Collection) {
            return toJsonString((Collection) value);
        } else {
            return String.valueOf(value);
        }
    }
}

Related

  1. toBean(Class clazz, String json)
  2. toJson(E e)
  3. toJSON(Map map)
  4. toJson(Object object)
  5. toJson(Object object, String dateFormat)
  6. toList(String json, Class clz)
  7. toLocalJson(Object value, int depth)