Java解析Json資料的兩種方式
阿新 • • 發佈:2019-01-05
JSON資料解析的有點在於他的體積小,在網路上傳輸的時候可以更省流量,所以使用越來越廣泛,下面介紹使用JsonObject和JsonArray的兩種方式解析Json資料。
使用以上兩種方式解析json均需要依賴json-lib.jar開發包使用依賴包
1、JsonObject
使用JsonObject解析只有一條資料的json是非常方便的例如:"{\"name\":\"zhangsan\",\"password\":\"zhangsan123\",\"email\":\"[email protected]\"}"
public static void main(String[] args) {
String jsonString ="{\"name\":\"zhangsan\",\"password\":\"zhangsan123\",\"email\":\" [email protected]\"}";
JSONObject json = JSONObject.fromObject(jsonString);
User user = new User();
user.setName(json.getString("name"));
user.setPassword(json.getString("password"));
user.setEmail(json.getString("email"));
System.out.println(user.toString());
}
2、JsonArray
使用JsonArray 解析陣列資料的json是非常方便的例如:"[{\"name\":\"zhangsan\",\"password\":\"zhangsan123\",\"email\":\"[email protected]\"},{\"name\":\"lisi\",\"password\":\"lisi123\",\"email\":\"[email protected]\"}]"
String json = <span style="color: rgb(51, 51, 51); font-family: Arial; font-size: 14px; line-height: 26px;">"[{\"name\":\"zhangsan\",\"password\":\"zhangsan123\",\"email\":\" [email protected]\"},</span><span style="color: rgb(51, 51, 51); font-family: Arial; font-size: 14px; line-height: 26px;">{\"name\":\"lisi\",\"password\":\"lisi123\",\"email\":\"[email protected]\"}</span><span style="color: rgb(51, 51, 51); font-family: Arial; font-size: 14px; line-height: 26px;">]"</span>;
JSONArray jsonArray = JSONArray.fromObject(json);
ArrayList<User> users = new ArrayList<User>();
for (int i = 0; i < jsonArray.size(); i++) {
User userM = new User();
user.setName(jsonArray.getJSONObject(i).getString("name"));
user.setpassword(jsonArray.getJSONObject(i).getString("password"));
user.setEmail(jsonArray.getJSONObject(i).getString("email"));
users.add(user);
}
for (User user : users) {
System.out.println(user.toString());
}
通過以上兩種方式可以解析不同格式的json資料