package json;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
public class Jsonhelper
{
public static void main(String[] args)
{
List list = new ArrayList();
for (int i = 0; i < 10; ++i)
list.add(Integer.valueOf(i));
System.out.println(list.toString());
String[] li = { "1", "2" };
System.out.println(li.toString());
System.out.println(StringUtils.join(li, "'"));
}
public static String getJson(Object o) {
JSONObject jo = JSONObject.fromObject(o);
return jo.toString();
}
public static String getJson(List list) {
JSONArray ja = JSONArray.fromObject(list);
return ja.toString();
}
public static String getJson(Object[] arry) {
JSONArray ja = JSONArray.fromObject(arry);
return ja.toString();
}
public static Map getObject(String s) {
return JSONObject.fromObject(s);
}
public static List getArray(String s) {
return JSONArray.fromObject(s);
}
public static Object getObject(String s, Class cls) {
JSONObject jo = JSONObject.fromObject(s);
return JSONObject.toBean(jo, cls);
}
public static Object getArray(String s, Class cls) {
JSONArray ja = JSONArray.fromObject(s);
return JSONArray.toArray(ja, cls);
}
public static void ex1() {
JSONObject obj = new JSONObject();
obj.put("derek", "23");
obj.put("dad", "49");
obj.put("mom", "45");
System.out.println("通过构造器的方式创建的JSONObject对象:" + obj);
Map map = new LinkedHashMap();
map.put("derek", "23");
map.put("dad", "49");
map.put("mom", "45");
System.out.println("通过fromObject方法将map对象转换为JSONObject对象:" + JSONObject.fromObject(map));
JSONArray arr = new JSONArray();
arr.add(0, "derek");
arr.add(1, "dad");
arr.add(2, "mom");
System.out.println("通过构造器的方式创建的JSONArray:" + arr);
ArrayList list = new ArrayList();
list.add("derek");
list.add("dad");
list.add("mom");
System.out.println("通过fromObject方法将Arraylist对象转换为JSONArray对象:" + JSONArray.fromObject(list));
System.out.println("将HashMap对象通过fromObject方法转换为JSONArray对象" + JSONArray.fromObject(map));
String str = "{'derek':23,'dad':49,'mom':45}";
System.out.println("解析之后的JSON对象:" + JSONObject.fromObject(str));
Iterator it = obj.keys();
while (it.hasNext()) {
String key = (String)it.next();
System.out.println(key + ":" + obj.get(key));
}
// JSONArray array = JSONArray.fromObject(json);
// Book[] books = (Book[])JSONArray.toArray(array, Book.class);
}
}