package Sojson;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
/**
*
* 开发公司:itboy.net
* 版权:itboy.net
*
*
* JSON工具类
*
*
*
* 区分 责任人 日期 说明
* 创建 周柏成 2015年12月25日
*
* *******
*
* @author zhou-baicheng
* @email i@itboy.net
* @version 1.0,2015年12月25日
*
*/
public class JSONUtils {
/**
* 格式化日期
*/
private static final SimpleDateFormat FMT = new SimpleDateFormat(
"yyyy-MM-dd");
private Map jsonMap = new HashMap();
/**
* 清理map
* @author zhou-baicheng
*/
public void clear() {
jsonMap.clear();
}
/**
* 添加元素
* @author zhou-baicheng
* @param key 键
* @param value 值
* @return Map
*/
public Map put(String key, Object value) {
jsonMap.put(key, value);
return jsonMap;
}
/**
* 判断是否要加引号
* return (value instanceof Integer || value instanceof Boolean
* || value instanceof Double || value instanceof Float
* || value instanceof Short || value instanceof Long || value
* instanceof Byte);
* @author zhou-baicheng
* @param value
* @return boolean
*/
private static boolean isNoQuote(Object value) {
if (value instanceof Integer) {
return true;
} else if (value instanceof Boolean) {
return true;
} else if (value instanceof Double) {
return true;
} else if (value instanceof Float) {
return true;
} else if (value instanceof Short) {
return true;
} else if (value instanceof Long) {
return true;
} else if (value instanceof Byte) {
return true;
} else {
return false;
}
}
/**
* 判断是否要加引号
* @author zhou-baicheng
* @param value
* @return boolean
*/
private static boolean isQuote(Object value) {
if (value instanceof String) {
return true;
} else if (value instanceof Character) {
return true;
} else {
return false;
}
}
/**
* 返回形如{'apple':'red','lemon':'yellow'}的字符串
* @author zhou-baicheng
* @return String
* @see java.lang.Object#toString()
*/
@SuppressWarnings("unchecked")
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("{");
Set> set = jsonMap.entrySet();
for (Entry entry : set) {
Object value = entry.getValue();
if (value == null) {
continue;// 对于null值,不进行处理,页面上的js取不到值时也是null
}
sb.append("'").append(entry.getKey()).append("':");
if (value instanceof JSONUtils) {
sb.append(value.toString());
} else if (isNoQuote(value)) {
sb.append(value);
} else if (value instanceof Date) {
sb.append("'").append(FMT.format(value)).append("'");
} else if (isQuote(value)) {
sb.append("'").append(value).append("'");
} else if (value.getClass().isArray()) {
sb.append(arrayToStr(value));
} else if (value instanceof Map) {
sb.append(fromObject((Map) value).toString());
} else if (value instanceof List) {
sb.append(listToStr((List