Java uses reflection to convert Pojo to JSON objects

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.