package cn.jstorm.json;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class Json {
public static List<Object> toList(String jsonStr) {
if (StringUtils.isBlank(jsonStr)) {
return new ArrayList<Object>();
}
JSONArray jsonArray = JSONArray.fromObject(jsonStr);
List<Object> list = (List<Object>) JSONArray.toList(jsonArray);
return list;
}
public static Map<String, Object> toMap(String jsonStr) {
Map<String, Object> data = new HashMap<String, Object>();
// 将json字符串转换成jsonObject
JSONObject jsonObject = JSONObject.fromObject(jsonStr);
Iterator<Object> it = jsonObject.keys();
// 遍历jsonObject数据,添加到Map对象
while (it.hasNext()) {
String key = String.valueOf(it.next());
Object value = jsonObject.get(key);
data.put(key, value);
}
return data;
}
public static String lsToJson(List<Object> ls) {
JSONArray json = JSONArray.fromObject(ls);
return json.toString();
}
public static String mapToJson(Map<String, Object> map) {
JSONObject json = JSONObject.fromObject(map);
return json.toString();
}
public static void main(String[] args) {
List<Object> ls = new ArrayList<Object>();
User user = new User();
user.setName("jack lin");
user.setBirthday(new Date());
user.setAge(18);
ls.add("my pic");
ls.add(119);
ls.add(new Date());
ls.add(user);
Map<String ,Object> map = new HashMap<String, Object>();
map.put("list", ls);
map.put("str", "string");
map.put("int", 10000);
map.put("Date", new Date());
String map_str = Json.mapToJson(map);
Map<String,Object> rm = Json.toMap(map_str);
List<Object> l = (List<Object>) rm.get("list");
for (Object object : l) {
System.out.println(object);
}
System.out.println(new Date());
String ls_str = Json.lsToJson(ls);
System.out.println(ls_str);
List<Object> rl = Json.toList(ls_str);
System.out.println(rl.toString());
}
}