最近做以太坊钱包项目需要与前台进行json交互,写一个工具类,经普通javaBean转为json对象
package util; import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List; import org.web3j.protocol.core.methods.response.Transaction; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; public class JSONUtil { /**
* 获取Transaction相应的JSON对象
* @param trans
* @return
*/
public static JSONObject getTransJSON(Transaction trans) {
JSONObject data = getJSON(Transaction.class, trans);
return data;
} /**
* 获取交易信息列表
* @param transList
* @return
*/
public static JSONArray getTransListJSON(List<Transaction> transList) {
JSONArray data = new JSONArray();
for(Transaction trans : transList) {
JSONObject transJson = getTransJSON(trans);
data.add(transJson);
}
return data;
} /**
* 获取json对象
* @param cls
* @param obj
* @return
*/
public static JSONObject getJSON(Class<?> cls, Object obj) {
JSONObject json = new JSONObject();
Field[] fieldArray = cls.getDeclaredFields();
for(Field field : fieldArray) {
String fieldName = field.getName();
String methodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
try {
Method method = cls.getMethod(methodName);
Object fieldObject = method.invoke(obj, new Object[0]);
String fieldValue = null;
if(fieldObject != null) {
fieldValue = fieldObject.toString();
}
json.put(fieldName, fieldValue);
} catch (Exception e) {
e.printStackTrace();
}
}
return json;
} }