JSON学习-org.json

package json;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class Start {

/**
* @param args
* @throws JSONException
* 一个{}代表一个非基本类型对象,一个:前面的代表的是域名,:后面的代表数值([]则代表域名是数组类型)
*/
public static void main(String[] args) throws JSONException {
// TODO Auto-generated method stub

Integer[] a ={1,2,3,4,5,6};
String b="wangyuelin";
List l = new ArrayList();
l.add("1");
l.add("2");
System.out.println(new JSONArray(a));            //[1,2,3,4,5,6]

// System.out.println(new JSONArray(b));            //ERROR: AJSONArray text must start with '[' at character 1 必须是数组


System.out.println(new JSONArray(b.toCharArray())); //["w","a","n","g","y","u","e","l","i","n"]
                System.out.println(new JSONArray(l));                    //["1","2"]

                System.out.println("******************");

System.out.println(new JSONObject(a));               //{}
// System.out.println(new JSONObject(b));           //ERROR: A JSONObject text must begin with '{' at character 1

 

//String在JSONObject中比较特殊,他需要正确的JSON格式 才可以运作,比如

 

System.out.println(new JSONObject("{'name':'wangyuelin'}"));  //{"name":"wangyuelin"}
System.out.println(new JSONObject(new Student()));  //Student中必须含有get方法才可以得到正确的 jsonobject,否则为空{}    {"address":"suzhou","name":"wangyuelin","age":12}
System.out.println(new JSONObject((Object)b));     

//自动调用了getBytes()和isEmpty()无参方法:{"bytes":[119,97,110,103,121,117,101,108,105,110],"empty":false}

 

System.out.println(new JSONObject(l));              //ArrayList中isEmpty()的无参构造方法,故为{}

System.out.println("******************");           //以键值对的形式放入


JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "wangyuelin");
jsonObject.put("sex", "男");  
jsonObject.put("QQ", "413425430"); 

jsonObject.put("student",new JSONObject(new Student()));  // 加入新object,以键值对形式(String :

String)形式存入


System.out.println(jsonObject);                       //{"sex":"男","QQ":"413425430","name":"wangyuelin"}


System.out.println("******************");           //增加JSONArray


JSONArray ja = new JSONArray();
ja.put(0,"1");
ja.put(1,"2");
ja.put(2,"3");                                    
jsonObject.put("我来数数", ja);
System.out.println(jsonObject);
}

}

 

你可能感兴趣的:(json,qq)