标签:对象 反序列化 epo 阿里巴巴 get use hone repos 举例
fastjson是阿里巴巴的开源JSON解析库,它可以解析JSON格式的字符串,支持将Java Bean序列化为JSON字符串,也可以从JSON字符串反序列化到JavaBean。
在pom.xml文件引入以下声明,就可以使用
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.55</version> </dependency>
使用举例:
1,解析成字符串
HashMap map = new HashMap(); ArrayList<String> list = new ArrayList<String>(); list.add("a"); list.add("b"); list.add("c"); map.put("count", 12); map.put("list", list); System.out.println(JSON.toJSONString(map)); // {"count":12,"list":["a","b","c"]}
2,对象解析成json字符串
public class User { private int id; private String phone; private String password; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
User user = new User(); user.setId(1); user.setPassword("11"); user.setPhone("11"); System.out.println(JSON.toJSONString(user)); // {"id":1,"password":"11","phone":"11"}
3,json字符串解析成对象
String json = "{‘id‘:‘1‘,‘password‘:‘11‘,‘phone‘:‘11‘}"; JSONObject userJson = JSONObject.parseObject(json); User user = JSON.toJavaObject(userJson, User.class); System.out.println(user); System.out.println(user.getId()); // com.test.domain.User@443b7951 // 1
标签:对象 反序列化 epo 阿里巴巴 get use hone repos 举例
原文地址:https://www.cnblogs.com/luoa/p/10544943.html