1、在pom.xml中添加依赖包
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.46</version>
</dependency>
2、创建测试类(JSONTest6.java)
package com.jeff;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jeff.entity.User;
public class JSONTest6 {
public static void main(String[] args) {
User user = new User();
user.setUserName("张三");
user.setPassword("123456");
user.setAge(18);
beanToJSONObject(user);
}
/**
*
* @description: 对象转JSON对象
* @author: Jeff
* @date: 2019年12月15日
* @param bean
*/
public static void beanToJSONObject(User bean) {
JSONObject jsonObject = (JSONObject) JSON.toJSON(bean);
String userName = jsonObject.getString("userName");
String password = jsonObject.getString("password");
Integer age = jsonObject.getInteger("age");
System.out.println("userName:" + userName + ",password:" + password + ",,age:" + age);
}
}
3、控制台输出结果