public static String objToJson(Object obj) {
StringBuilder json = new StringBuilder();
if (obj == null) {
json.append("\"\"");
} else if (obj instanceof Number) {
Number num = (Number)obj;
json.append(num.toString());
} else if (obj instanceof Boolean) {
Boolean bl = (Boolean)obj;
json.append(bl.toString());
} else if (obj instanceof String) {
json.append("\"").append(stringToJson(obj.toString())).append("\"");
} else if (obj instanceof Object[]) {
json.append(arrayToJson((Object[]) obj));
} else if (obj instanceof List) {
json.append(listToJson((List) obj));
} else if (obj instanceof Map) {
json.append(mapToJson((Map) obj));
} else if (obj instanceof Set) {
json.append(setToJson((Set) obj));
} else {
json.append(beanToJson(obj));
}
return json.toString();
}
/**
* @Title: json2Map
* @Creater: chencc <br>
* @Date: 2011-3-28 <br>
* @Description: TODO转化json2map
* @param @param jsonString
* @param @return
* @return Map<String,Object>
* @throws
*/
@SuppressWarnings("unchecked")
public static Map<String, Object> json2Map(String jsonString) {
Map<String, Object> map = new HashMap<String, Object>();
try {
if(null != jsonString && !"".equals(jsonString)){
JSONObject jsonObject = new JSONObject(jsonString);
Iterator keyIter = jsonObject.keys();
String key = "";
Object value = null;
while (keyIter.hasNext()) {
key = (String) keyIter.next();
value = jsonObject.get(key);
map.put(key, value);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
//测试方法
public static void main(String[] args) {
Map<String,Object> params = new HashMap<String,Object>();
params.put("callId123", Integer.valueOf(1000));
Map retMap = new HashMap();
retMap.put("params", params);
retMap.put("result", true);
List ls = new ArrayList();
ls.add(new HashMap());
ls.add("hello world!!");
ls.add(new String[4]);
retMap.put("list", ls);
String[] strArray = new String[10];
strArray[1]="first";
strArray[2]="2";
strArray[3]="3";
System.out.println("Boolean:"+JsonUtils.objToJson(true));
System.out.println("Number:"+JsonUtils.objToJson(23.3));
System.out.println("String:"+JsonUtils.objToJson("sdhfsjdgksdlkjfk\"sd,!#%$^&*#(*@&*%&*$fsdfsdfsdf"));
System.out.println("Map :"+JsonUtils.objToJson(retMap));
System.out.println("List:"+JsonUtils.objToJson(ls));
System.out.println("Array:"+JsonUtils.objToJson(strArray));
String json = JsonUtils.objToJson(retMap);
Map r = JsonUtils.json2Map(json);
System.out.println(r.get("callId123"));
}
}
再来聊聊net.sf.json.JSONObject这个JSONObject,代码如下