一、依赖
fastjson-1.2.83.jar
二、实体类
package com.chenwc;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 心跳包
* @author chenwc
* @date 2023/2/19 0:12
*/
public class OK {
//状态
private boolean status;
//生成心跳包的时间
private String time;
//心跳包来源
private String from;
//信息
private String msg;
public static OK ok(){
return new OK(true, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date()), "server", "KeepAlive");
}
public OK(boolean status, String time, String from, String msg) {
this.status = status;
this.time = time;
this.from = from;
this.msg = msg;
}
public OK() {
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
三、测试
package com.chenwc;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.fastjson.JSONObject;
public class Test {
public static void main(String[] args) {
// TODO 自动生成的方法存根
System.out.println(objectToJSONObject(OK.ok()));
System.out.println(objectToMap(OK.ok()));
}
/**
* 对象转化为 JSONObject
*
* @param obj 需要转换的对象
* @return JSONObject
*/
public static JSONObject objectToJSONObject(Object obj) {
if (obj == null) {
return null;
}
JSONObject jsonObject = new JSONObject();
try {
Field[] declaredFields = obj.getClass().getDeclaredFields();
for (Field field : declaredFields) {
field.setAccessible(true);
jsonObject.put(field.getName(), field.get(obj));
}
} catch (Exception e) {
e.printStackTrace();
}
return jsonObject;
}
/**
* 对象转化为 Map
*
* @param obj 需要转换的对象
* @return map
*/
public static Map<String, Object> objectToMap(Object obj) {
if (obj == null) {
return null;
}
Map<String, Object> map = new HashMap<>();
try {
Field[] declaredFields = obj.getClass().getDeclaredFields();
for (Field field : declaredFields) {
field.setAccessible(true);
map.put(field.getName(), field.get(obj));
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
}