Recently done Ethereum Wallet project need to interact with the foreground JSON, write a tool class, by ordinary JavaBean to JSON object
1 Packageutil;2 3 ImportJava.lang.reflect.Field;4 ImportJava.lang.reflect.Method;5 Importjava.util.List;6 7 Importorg.web3j.protocol.core.methods.response.Transaction;8 9 ImportCom.alibaba.fastjson.JSONArray;Ten ImportCom.alibaba.fastjson.JSONObject; One A Public classJsonutil { - - /** the * Get transaction The corresponding JSON object - * @paramTrans - * @return - */ + Public Staticjsonobject Gettransjson (Transaction trans) { -Jsonobject data = Getjson (Transaction.class, trans); + returndata; A } at - /** - * Get a list of trading information - * @paramtranslist - * @return - */ in Public StaticJsonarray Gettranslistjson (list<transaction>translist) { -Jsonarray data =NewJsonarray (); to for(Transaction trans:translist) { +Jsonobject Transjson =Gettransjson (trans); - Data.add (Transjson); the } * returndata; $ }Panax Notoginseng - /** the * Get JSON object + * @paramCLS A * @paramobj the * @return + */ - Public StaticJsonobject Getjson (class<?>cls, Object obj) { $Jsonobject JSON =NewJsonobject (); $field[] Fieldarray =cls.getdeclaredfields (); - for(Field field:fieldarray) { -String FieldName =field.getname (); theString methodName = "Get" + fieldname.substring (0, 1). toUpperCase () + fieldname.substring (1); - Try {WuyiMethod method =Cls.getmethod (methodName); theObject fieldobject = Method.invoke (obj,NewObject[0]); -String Fieldvalue =NULL; Wu if(Fieldobject! =NULL) { -Fieldvalue =fieldobject.tostring (); About } $ json.put (FieldName, fieldvalue); -}Catch(Exception e) { - e.printstacktrace (); - } A } + returnJSON; the } - $}
Java uses reflection to convert Pojo to JSON objects