//使用new JSONObject()构造一个JSON对象,参数为空
public
String jsonTest()
throws
JSONException{
JSONObject json=
new
JSONObject();
JSONArray jsonMembers =
JSONArray();
JSONObject member1 =
JSONObject();
member1.put(
"loginname"
,
"jack"
);
"password"
"userpass"
);
"email"
"fbeiwb@163.com"
);
"sign_date"
"2007-06-12"
);
jsonMembers.put(member1);
JSONObject member2 =
JSONObject();
member2.put(
"tom"
);
);
"123123@126.com"
);
"2008-07-16"
);
jsonMembers.put(member2);
return
json.toString();
}
//从字符串构造一个JSON对象并解析之
String jsonTest2()
JSONException{
String jsonString=
"{\"users\":[{\"loginname\":\"jack\",\"password\":\"userpass\",\"email\":\"fbeiwb@163.com\"},{\"loginname\":\"tom\",\"email\":\"1231231@163.com\"}]}"
;
JSONObject json=
JSONObject(jsonString);
JSONArray jsonArray=json.getJSONArray(
);
String loginNames=
"loginname list:"
;
for
(
int
i=
0
;i<jsonArray.length();i++){
JSONObject user=(JSONObject) jsonArray.get(i);
String userName=(String) user.get(
);
if
(i==jsonArray.length()-
1
){
loginNames+=userName;
}
else
{
loginNames+=userName+
","
;
}
}
loginNames;
}
原文链接:https://www.f2er.com/json/290324.html