java利用反射将pojo转为json对象
最近做以太坊钱包项目需要与前台进行json交互,写一个工具类,经普通javaBean转为json对象
1 package util;
2
3 import java.lang.reflect.Field;
4 import java.lang.reflect.Method;
5 import java.util.List;
6
7 import org.web3j.protocol.core.methods.response.Transaction;
8
9 import com.alibaba.fastjson.JSONArray;
10 import com.alibaba.fastjson.JSONObject;
11
12 public class JSONUtil {
13
14 /**
15 * 获取Transaction相应的JSON对象
16 * @param trans
17 * @return
18 */
19 public static JSONObject getTransJSON(Transaction trans) {
20 JSONObject data = getJSON(Transaction.class, trans);
21 return data;
22 }
23
24 /**
25 * 获取交易信息列表
26 * @param transList
27 * @return
28 */
29 public static JSONArray getTransListJSON(List<Transaction> transList) {
30 JSONArray data = new JSONArray();
31 for(Transaction trans : transList) {
32 JSONObject transJson = getTransJSON(trans);
33 data.add(transJson);
34 }
35 return data;
36 }
37
38 /**
39 * 获取json对象
40 * @param cls
41 * @param obj
42 * @return
43 */
44 public static JSONObject getJSON(Class<?> cls, Object obj) {
45 JSONObject json = new JSONObject();
46 Field[] fieldArray = cls.getDeclaredFields();
47 for(Field field : fieldArray) {
48 String fieldName = field.getName();
49 String methodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
50 try {
51 Method method = cls.getMethod(methodName);
52 Object fieldObject = method.invoke(obj, new Object[0]);
53 String fieldValue = null;
54 if(fieldObject != null) {
55 fieldValue = fieldObject.toString();
56 }
57 json.put(fieldName, fieldValue);
58 } catch (Exception e) {
59 e.printStackTrace();
60 }
61 }
62 return json;
63 }
64
65 }