list To Json String - Android java.util

Android examples for java.util:List

Description

list To Json String

Demo Code


//package com.java2s;

import java.util.List;

public class Main {

    @SuppressWarnings("rawtypes")
    public static String listToJsonString(List list) {
        if (list == null || list.size() == 0) {
            return "[]";
        }/*from  ww  w  .ja v  a 2s.c o  m*/
        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