说明:JSONObject用net.sf.json.JSONObject,不要用com.alibaba.fastjson.JSONObject
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class jsonTest {
public static void main(String[] args) {
//定义两种不同格式的字符串
String objectStr="{\"name\":\"JSON\",\"age\":24,\"address\":\"北京市西城区\"}";
String arrayStr="[{\"name\":\"JSON\",\"age\":\"24\",\"address\":\"北京市西城区\"}]";
//1、使用JSONObject
JSONObject jsonObject=JSONObject.fromObject(objectStr);
System.out.println("stu:"+jsonObject.toString());
String name=(String)jsonObject.get("name");
Integer age=(Integer)jsonObject.get("age");
System.out.println(name+","+age);
//2、使用JSONArray
JSONArray jsonArray=JSONArray.fromObject(arrayStr);
//获得jsonArray的第一个元素
Object o=jsonArray.get(0);
System.out.println("o:"+o.toString());
JSONObject jsonObject2=JSONObject.fromObject(o);
System.out.println("stu2:"+jsonObject2.toString());
}
}