1.json->java
2.java->json
3.bean数组->Json数组
4.json数组->bean集合
package bean; //实体类 public class User { private Integer id; private String name; private Integer age; public User() { } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}'; } public User(Integer id, String name, Integer age) { this.id = id; this.name = name; this.age = age; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
package test; import bean.User; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import java.util.ArrayList; import java.util.List; public class Demo { public static void main(String[] args) { //java->json User user = new User(1,"范一伟",18); JSONObject jsonObject = JSONObject.fromObject(user); System.out.println(jsonObject); System.out.println("==============="); //json->java String str1 = "{\"age\":18,\"id\":1,\"name\":\"范一伟\"}"; JSONObject jsonObject1 = JSONObject.fromObject(str1); Object o = JSONObject.toBean(jsonObject1,User.class); System.out.println(o); System.out.println("==================="); //ArrayList->json数组 List users = new ArrayList(); users.add(new User(1,"范一伟1",18)); users.add(new User(2,"范一伟2",18)); users.add(new User(3,"范一伟3",18)); JSONArray jsonArray = JSONArray.fromObject(users); System.out.println(jsonArray); System.out.println("===================="); //json数组->数组 String str2 = "[{\"age\":18,\"id\":1,\"name\":\"范一伟1\"},{\"age\":18,\"id\":2,\"name\":\"范一伟2\"},{\"age\":18,\"id\":3,\"name\":\"范一伟3\"}]"; JSONArray jsonArray1 = JSONArray.fromObject(str2); Object[] o1 = (Object[]) JSONArray.toArray(jsonArray, User.class); for (Object o2 : o1) { System.out.println(o2); } } }
ss);
for (Object o2 : o1) {
System.out.println(o2);
}
}
}
## 3.相关jar包 ![在这里插入图片描述](https://www.www.zyiz.net/i/ll/?i=dd80fb258cc64feb84f715876b3b0f70.png#pic_center)