创建json:
//construct json and output it
public String jsonTest() throws JSONException{
JSONObject json=new JSONObject();
JSONArray jsonMembers = new JSONArray();
JSONObject member1 = new JSONObject();
member1.put("loginname", "zhangfan");
member1.put("password", "userpass");
member1.put("email","[email protected]");
member1.put("sign_date", "2007-06-12");
jsonMembers.put(member1);
JSONObject member2 = new JSONObject();
member2.put("loginname", "zf");
member2.put("password", "userpass");
member2.put("email","[email protected]");
member2.put("sign_date", "2008-07-16");
jsonMembers.put(member2);
json.put("users", jsonMembers);
return json.toString();
}
解析json:
//construct json from String and resolve it.
public String jsonTest2() throws JSONException{
String jsonString="{\"users\":[{\"loginname\":\"zhangfan\",\"password\":\"userpass\",\"email\":\"[email protected]\"},{\"loginname\":\"zf\",\"password\":\"userpass\",\"email\":\"[email protected]\"}]}";
JSONObject json= new JSONObject(jsonString);
JSONArray jsonArray=json.getJSONArray("users");
String loginNames="loginname list:";
for(int i=0;i<jsonArray.length();i++){
JSONObject user=(JSONObject) jsonArray.get(i);
String userName=(String) user.get("loginname");
if(i==jsonArray.length()-1){
loginNames+=userName;
}else{
loginNames+=userName+",";
}
}
return loginNames;
}