To partially update the properties of a javabean by using reflection to implement JSON data

Source: Internet
Author: User

The job encountered a requirement to update the Java object based on the return JSON. Read the data, wrote a tool class, and learned that reflection gets the set generic type. The JSON class library in the code is Fastjson

1  Public classJsonutil {2 3     /**4 * JavaBean properties are more than JSON, updating JavaBean the same name field values based on JSON5      *6      * @paramBean7      * @paramJSON8      * @param<T>9      */Ten      Public Static<T>voidPatchupdate (T Bean, jsonobject JSON)throwsException { Oneset<string> keys =Json.keyset (); Afield[] Fields =Bean.getclass (). Getdeclaredfields (); -          for(String key:keys) { -              for(Field field:fields) { the                 if(Field.getname (). Equals (key)) { -String value =json.getstring (key); -String type =Field.gettype (). toString (); -Field.setaccessible (true); +                     if(Type.endswith ("String")) { - Field.set (bean, value); +}Else if(Type.endswith ("int")) { A Field.set (Bean, Integer.parseint (value)); at}Else if(Type.endswith ("Double")) { - Field.set (Bean, double.parsedouble (value)); -}Else if(Type.endswith ("Date")) { -DateFormat Fmtdatetime =NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); -Date Date =Fmtdatetime.parse (value); - Field.set (bean, date); in}Else if(Type.endswith ("List")) { -                         //gets the type of List first:java.util.list<e> toParameterizedtype pt =(Parameterizedtype) Field.getgenerictype (); +                         //Get generics: E -Class E = (Class) pt.getactualtypearguments () [0]; theList List =Jsonarray.parsearray (value, e); * field.set (bean, list); $                     }Panax Notoginseng                 } -             } the         } +     } A}

To partially update the properties of a javabean by using reflection to implement JSON data

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.