在工作中,经常会将JSON串转换映射成java对象,如下是fastjson和jsonLib将JSON串转换成JAVA对象的实例,特在此记录。
工程结构:
UserInfo.java
class="java" name="code">package com.bijian.test; public class UserInfo { private String name; private int age; private String address; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "UserInfo [name=" + name + ", age=" + age + ", address=" + address + "]"; } }
Main.java
package com.bijian.test; import com.alibaba.fastjson.JSON; import net.sf.json.JSONObject; public class Main { private static String jsonStr = "{\"name\":\"zhangshan\", \"age\": 10, \"address\": \"中国深圳\"}"; public static void main(String[] args) { //JSON-LIB JSONObject jsonResult = JSONObject.fromObject(jsonStr); UserInfo userInfo = (UserInfo)JSONObject.toBean(jsonResult, UserInfo.class); System.out.println("userInfo:" + userInfo); //fastjson com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(jsonStr); UserInfo userInfo2 = com.alibaba.fastjson.JSONObject.toJavaObject(jsonObject, UserInfo.class); System.out.println("userInfo2:" + userInfo2); } }
?运行结果:
userInfo:UserInfo [name=zhangshan, age=10, address=中国深圳] userInfo2:UserInfo [name=zhangshan, age=10, address=中国深圳]
当然,json-lib的使用坑可以进一步查看《JSONObject以及json串》一文了解。