Json数据和实体类之间转换
1.json->java
2.java->json
3.bean数组->Json数组
4.json数组->bean集合
1.实体类
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;
}
}
2.转换过程
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) {
User user = new User(1,"范一伟",18);
JSONObject jsonObject = JSONObject.fromObject(user);
System.out.println(jsonObject);
System.out.println("===============");
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("===================");
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("====================");
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);
}
}
}
3.相关jar包
ss); for (Object o2 : o1) { System.out.println(o2); }
}
}
## 3.相关jar包
![在这里插入图片描述](https://img-blog.csdnimg.cn/dd80fb258cc64feb84f715876b3b0f70.png#pic_center)
|