记录了fastjson中常用的对象之间的转换的方法,直接步入正题
fastjson需要的依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
JSONObject、JavaBean、jsonString 互转
// 准备一个JavaBean类,需要提供 有参构造、无参构造、get/set、toString等方法
public class User implements Serializable {
private Integer id;
private String name;
private String password;
}
// 测试
public class JsonTest {
public static void main(String[] args) {
User user = new User(1, "aaa", "123"); // javaBean
JSONObject jsonObject = null; // jsonObject
String jsonString = null; // jsonString
System.out.println("\njavaBean --> JSONObject : JSON.toJSON");
jsonObject = (JSONObject) JSON.toJSON(user);
System.out.println(jsonObject);
System.out.println("\njavaBean --> jsonString : JSON.toJSONString");
jsonString = JSON.toJSONString(user);
System.out.println(jsonString);
System.out.println("\njsonString --> JSONObject : JSON.parseObject");
jsonObject = JSON.parseObject(jsonString);
System.out.println(jsonObject);
System.out.println("\njsonString --> javaBean : JSON.parseObject");
User user1 = JSON.parseObject(jsonString, User.class);
System.out.println(user1);
System.out.println("\nJSONObject --> jsonString : JSON.toJSONString");
jsonString = JSON.toJSONString(jsonObject);
System.out.println(jsonString);
System.out.println("\nJSONObject --> javaBean : JSON.toJavaObject");
User user2 = JSON.toJavaObject(jsonObject, User.class);
System.out.println(user2);
}
}