hash Table To Json String - Android java.util

Android examples for java.util:Hashtable

Description

hash Table To Json String

Demo Code


//package com.java2s;

import java.io.Serializable;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;

public class Main {

    @SuppressWarnings("unchecked")
    public static String hashTableToJsonString(
            Hashtable<String, Serializable> hashtable) {
        if (hashtable == null) {
            return "{}";
        }//from   w  w  w  .ja  v  a2 s . com

        Enumeration<String> enumerationKeys = hashtable.keys();
        Boolean alreadyAddParma = false;
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("{");
        while (enumerationKeys.hasMoreElements()) {
            if (alreadyAddParma) {
                stringBuilder.append(",");
            }
            String key = (String) enumerationKeys.nextElement();

            Object valuesObject = hashtable.get(key);
            if (valuesObject instanceof Hashtable<?, ?>) {
                stringBuilder
                        .append("\""
                                + key
                                + "\":"
                                + hashTableToJsonString((Hashtable<String, Serializable>) valuesObject));
            } else if (valuesObject instanceof List) {
                stringBuilder.append("\"" + key + "\":"
                        + listToJsonString((List<?>) valuesObject));
            } else {
                stringBuilder.append("\"" + key + "\":"
                        + fomatValue(valuesObject));
            }
            alreadyAddParma = true;
        }
        stringBuilder.append("}");
        return stringBuilder.toString();
    }

    @SuppressWarnings("rawtypes")
    public static String listToJsonString(List list) {
        if (list == null || list.size() == 0) {
            return "[]";
        }
        Boolean alreadyAddParam = false;
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("[");
        for (Object object : list) {
            if (alreadyAddParam) {
                stringBuilder.append(",");
            }
            stringBuilder.append(fomatValue(object));
            alreadyAddParam = true;
        }
        stringBuilder.append("]");
        return stringBuilder.toString();
    }

    public static String fomatValue(Object object) {
        if (object == null) {
            return "\"\"";
        }
        StringBuilder stringBuilder = new StringBuilder();
        if (object instanceof String) {
            stringBuilder.append("\"" + String.valueOf(object) + "\"");
        } else if (object instanceof Integer || object instanceof Long
                || object instanceof Boolean) {
            stringBuilder.append("" + object + "");
        } else {
            stringBuilder.append("\"" + object + "\"");
        }
        return stringBuilder.toString();
    }
}

Related Tutorials