Java 处理 JSON
Java 处理 JSON 需要的第三方库:
对于与 JSONObject 进行转化的 Java 对象,都要将其实现为一个 JavaBean;关于 JavaBean 最简单的规定如下:
以下是示例用的JavaBean1public class User {2 private String first = null;3 private String lastName = null;4 public User() {5 }6 public User(String first, String lastName) {7 this.first = first;8 this.lastName = lastName;9 }10 public String getFirst() {11 return first;12 }13 public void setFirst(String first) {14 this.first = first;15 }16 public String getLastName() {17 return lastName;18 }19 public void setLastName(String lastName) {20 this.lastName = lastName;21 }22}将 Java 对象转化为 JSON 字符串要将 Java 对象转化的 JSON 格式的字符串,要先确保该 Java 对象已经实现为一个JavaBean,首先将 Java 对象转化为 JSONObject对象,再转化为字符串;1User user = new User("Alssad","Alex");23JSONObject jsonObj = JSONObject.fromObject(user);4String jsonStr = jsonObj.toString();56//jsonStr内容: 7{"lastName":"Alex","first":"Alssad"}
将 Java 对象列表转化为 JSONArray,并转化为字符串要将 Java 对象列表转化的 JSON 格式的字符串,首先将 Java 对象列表转化为 JSONArray对象,再转化为字符串;
1List<User> list = new ArrayList<User>();2list.add(new User("John","Doe"));3list.add(new User("Anna","Smith"));4list.add(new User("Peter","Jones"));56JSONArray jsonArr = JSONArray.fromObject(list);7String jsonStr = jsonArr.toString();89//jsonStr内容: 10[{"lastName":"Doe","first":"John"},{"lastName":"Smith","first":"Anna"},{"lastName":"Jones","first":"Peter"}]
将 JSON 字符串转化为 Java 对象1//{"lastName":"Alex","first":"Alssad"}2String jsonStr = "{/"lastName/":/"Alex/",/"first/":/"Alssad/"}";34JSONObject jsonObj = JSONObject.fromObject(jsonStr);5User user = (User)JSONObject.toBean(jsonObj,User.class);
将 JSON 字符串转化为 Java 对象数组1//[{"lastName":"Doe","first":"John"},{"lastName":"Smith","first":"Anna"},{"lastName":"Jones","first":"Peter"}]2String jsonStr = "[{/"lastName/":/"Doe/",/"first/":/"John/"},{/"lastName/":/"Smith/",/"first/":/"Anna/"},{/"lastName/":/"Jones/",/"first/":/"Peter/"}]";34JSONArray jsonArray = JSONArray.fromObject(jsonStr);5List<User> list = (List<User>)JSONArray.toList(jsonArray,User.class);