Json数据和实体类之间转换
2021/9/24 6:12:45
本文主要是介绍Json数据和实体类之间转换,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
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) { //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); } } }
3.相关jar包
ss);
for (Object o2 : o1) {
System.out.println(o2);
}
}
}
## 3.相关jar包 ![在这里插入图片描述](https://www.www.zyiz.net/i/ll/?i=dd80fb258cc64feb84f715876b3b0f70.png#pic_center)
这篇关于Json数据和实体类之间转换的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-12-21Vue3教程:新手入门到实践应用
- 2024-12-21VueRouter4教程:从入门到实践
- 2024-12-20Vue3项目实战:从入门到上手
- 2024-12-20Vue3项目实战:新手入门教程
- 2024-12-20VueRouter4项目实战:新手入门教程
- 2024-12-20如何实现JDBC和jsp的关系?-icode9专业技术文章分享
- 2024-12-20Vue项目中实现TagsView标签栏导航的简单教程
- 2024-12-20Vue3入门教程:从零开始搭建你的第一个Vue3项目
- 2024-12-20从零开始学习vueRouter4:基础教程
- 2024-12-20Vuex4课程:新手入门到上手实战全攻略