Java uses reflection mapping JSON object as JavaBean

Source: Internet
Author: User
Tags addall reflection

About converting Jsonobject to JavaBean, in fact, there is a Tobean () method in Jsonobject to deal with, also can be based on a given jsonconfig to deal with the corresponding requirements, such as filtering the specified properties

[Java]View PlainCopyPrint?
  1. //Returns TRUE to filter out the attribute   
  2. Jsonconfig.setjsonpropertyfilter (new propertyfilter () {
  3. @Override   
  4. Public boolean apply (object o, String N, Object v) {
  5. return          false;
  6. }
  7. });
Returns true to filter out the attribute Jsonconfig.setjsonpropertyfilter (new PropertyFilter () {    @Override public    Boolean apply ( Object o, String N, Object v) {        return false;           }});  

set default values for some properties
[Java]View PlainCopyPrint?
  1. //When serializing to JSON, set the integer object to null   
  2. Jsonconfig.registerdefaultvalueprocessor (Integer. Class,
  3. New defaultvalueprocessor () {
  4. @SuppressWarnings ("unchecked")
  5. @Override   
  6. Public Object getdefaultvalue (Class type) {
  7. return   "";
  8. }
  9. });
When serializing to JSON, set the Integer object to Nulljsonconfig.registerdefaultvalueprocessor (Integer.class,    new Defaultvalueprocessor () {        @SuppressWarnings ("unchecked")        @Override public        Object Getdefaultvalue ( Class type) {            return "";        }});


There are other useful methods that are not introduced here ..., but in practice, the properties in the JavaBean that are converted to JSON objects may also be a JSON object or a JSON array, but in the property is a string type. This causes the type conversion to fail when the JSON object is converted to JavaBean. The method for Jsonconfig was looked up, and no method was found to process Jsonobject or Jsonarray as string in the Json-->bean process, so only reflection can be used to complete the mapping of special objects. Here's what to note:
[Java]View PlainCopyPrint?
    1. when Jsonobject encounters a JSON string that is NULL , it will return to Jsonnull.
When Jsonobject encounters a JSON string that is NULL, it returns JSONNULL


Therefore, you need to pay special attention when judging to be empty. The code is as follows [HTML]View PlainCopyPrint?
  1. public static examblobs Parsejsontoexam (Jsonobject obj) {
  2. Examblobs exam = new examblobs ();
  3. try {
  4. List<Field> fieldlist = new ArrayList   <Field>();
  5. FieldList
  6. . AddAll (Arrays.aslist (Exam.getclass (). Getdeclaredfields ()));
  7. for (Field field:fieldlist) {
  8. String name = field. GetName ();
  9. Object value = obj. Get (name);
  10. if (value! = NULL &&!) ( Value instanceof Jsonnull)) {
  11. Makes it possible to copy a private property
  12. Field.setaccessible (TRUE);
  13. if (Name.equalsignorecase ("Option")) {
  14. Jsonarray jarr = (jsonarray) value;
  15. Field.set (Exam, jarr.tostring ());
  16. } else {
  17. String type = field. GetType (). toString ();
  18. if (Type.indexof ("Integer") >= 0) {
  19. Field.set (Exam, (Integer) value);
  20. } else if (Type.indexof ("String") >= 0) {
  21. Field.set (Exam, (String) value);
  22. } else if (Type.indexof ("Date") >= 0) {
  23. Jsonobject dataobj = (jsonobject) value;
  24. Field.set (Exam,
  25. Jsonobject.tobean (Dataobj, Date.class));
  26. }
  27. }
  28. }
  29. }
  30. } catch (SecurityException e) {
  31. E.printstacktrace ();
  32. } catch (IllegalArgumentException e) {
  33. E.printstacktrace ();
  34. } catch (Illegalaccessexception e) {
  35. E.printstacktrace ();
  36. }
  37. return exam;
  38. }
public static examblobs Parsejsontoexam (Jsonobject obj) {examblobs exam = new Examblobs ();        try {list<field> fieldlist = new arraylist<field> ();        FieldList. AddAll (Arrays.aslist (Exam.getclass (). Getdeclaredfields ()));            for (Field field:fieldlist) {String name = Field.getname ();            Object value = obj.get (name); if (value! = NULL &&!) (                Value instanceof Jsonnull) {//makes it possible to copy field.setaccessible (true) to a private property;                    if (Name.equalsignorecase ("Option")) {Jsonarray Jarr = (jsonarray) value;                Field.set (Exam, jarr.tostring ());                    } else {String type = Field.gettype (). toString ();                    if (Type.indexof ("integer") >= 0) {field.set (exam, (integer) value); } else if (Type.indexof ("String") >= 0) {field.set (Exam, (striNG) value);                        } else if (Type.indexof ("Date") >= 0) {jsonobject dataobj = (jsonobject) value;                    Field.set (Exam, Jsonobject.tobean (dataobj, Date.class));    }}}}} catch (SecurityException e) {e.printstacktrace ();    } catch (IllegalArgumentException e) {e.printstacktrace ();    } catch (Illegalaccessexception e) {e.printstacktrace (); } return exam;}


Java uses reflection mapping JSON object as JavaBean

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.