Gson and Fastjson convert JSON objects to JavaBean simple controls

Source: Internet
Author: User
Tags tojson

My colleague left, and I took over the iteration and refactoring of the backend part of the project.

Looking at the project code today, the Discovery Project uses Gson to convert the JSON string to JavaBean.

Have not used Gson before, then, simply into the person,

Think of Fastjson also have to convert JSON string into JavaBean API, then simple comparison of the next source.

The APIs in Fastjson are as follows:

    /** * @since 1.2.9 * * Public <T> T tojavaobject (class<t> clazz) {return Typeutils.cast (    This, Clazz, parserconfig.getglobalinstance ()); } @SuppressWarnings ({"Unchecked", "rawtypes"}) public static <T> T cast (Object obj, class<t> clazz, Pa        Rserconfig config) {if (obj = = null) {return null;        } if (clazz = = null) {throw new IllegalArgumentException ("Clazz is null");        } if (Clazz = = Obj.getclass ()) {return (T) obj;            } if (obj instanceof Map) {if (clazz = = Map.class) {return (T) obj;            } map map = (map) obj; if (clazz = = Object.class &&!map.containskey (JSON.            Default_type_key)) {return (T) obj;        } return Casttojavabean ((map<string, object>) obj, clazz, config);     } if (Clazz.isarray ()) {if (obj instanceof Collection) {           Collection Collection = (Collection) obj;                int index = 0;                Object array = array.newinstance (Clazz.getcomponenttype (), collection.size ());                    For (object item:collection) {Object value = Cast (item, Clazz.getcomponenttype (), config);                    Array.set (array, index, value);                index++;            } return (T) array;            } if (clazz = = Byte[].class) {return (T) casttobytes (obj);        }} if (Clazz.isassignablefrom (Obj.getclass ())) {return (T) obj;        } if (clazz = = Boolean.class | | clazz = = boolean.class) {return (T) Casttoboolean (obj);        } if (clazz = = Byte.class | | clazz = = byte.class) {return (T) casttobyte (obj);        }//if (Clazz = = Char.class | | clazz = = character.class) {//Return (T) casttocharacter (obj); } if (Clazz = = Short.class | |        Clazz = = Short.class) {return (T) casttoshort (obj);        } if (clazz = = Int.class | | clazz = = integer.class) {return (T) casttoint (obj);        } if (clazz = = Long.class | | clazz = = long.class) {return (T) casttolong (obj);        } if (clazz = = Float.class | | clazz = = float.class) {return (T) casttofloat (obj);        } if (clazz = = Double.class | | clazz = = double.class) {return (T) casttodouble (obj);        } if (clazz = = String.class) {return (T) casttostring (obj);        } if (clazz = = Bigdecimal.class) {return (T) casttobigdecimal (obj);        } if (clazz = = Biginteger.class) {return (T) Casttobiginteger (obj);        } if (clazz = = Date.class) {return (T) casttodate (obj);        } if (clazz = = Java.sql.Date.class) {return (T) casttosqldate (obj); } if (clazz = = Java.sql.TiMestamp.class) {return (T) casttotimestamp (obj);        } if (Clazz.isenum ()) {return (T) casttoenum (obj, clazz, config);            } if (Calendar.class.isAssignableFrom (Clazz)) {Date date = Casttodate (obj);            Calendar Calendar;            if (clazz = = calendar.class) {Calendar = Calendar.getinstance (Json.defaulttimezone, Json.defaultlocale);                } else {try {calendar = (Calendar) clazz.newinstance ();                } catch (Exception e) {throw new Jsonexception ("Can not cast to:" + clazz.getname (), E);            }} calendar.settime (date);        return (T) calendar;            } if (obj instanceof string) {string strval = (string) obj; if (strval.length () = = 0//| | "null". Equals (Strval)//| |            "null". Equals (Strval)) {return null;      }      if (clazz = = Java.util.Currency.class) {return (T) java.util.Currency.getInstance (strval);    }} throw new Jsonexception ("Can not cast to:" + clazz.getname ()); } @SuppressWarnings ({"Unchecked"}) public static <T> T Casttojavabean (map<string, object> Map, CLASS&L T t> clazz, parserconfig config) {try {if (clazz = = Stacktraceelement.class) {String                Declaringclass = (String) map.get ("ClassName");                String methodName = (string) map.get ("MethodName");                string filename = (string) map.get ("FileName");                int linenumber;                    {Number value = (number) map.get ("linenumber");                    if (value = = null) {linenumber = 0;                    } else {linenumber = Value.intvalue (); }} return (T) New Stacktraceelement (DECLARingclass, MethodName, FileName, linenumber); } {Object iclassobject = Map.get (JSON.                Default_type_key);                    if (iclassobject instanceof string) {string className = (string) iclassobject;                    Class<?> Loadclazz = (class<t>) loadclass (className);                    if (Loadclazz = = null) {throw new ClassNotFoundException (ClassName + "not Found"); } if (!loadclazz.equals (Clazz)) {return (T) Casttojavabean (map, Loadclazz                    , config);                }}} if (Clazz.isinterface ()) {Jsonobject object;                if (map instanceof jsonobject) {object = (jsonobject) map;                } else {object = new Jsonobject (map);                 }return (T) proxy.newproxyinstance (Thread.CurrentThread (). Getcontextclassloader (), New class<?>[] {clazz}, object);} if (config = = null) {config = parserconfig.getglobalinstance ();            } Javabeandeserializer javabeandeser = null;            Objectdeserializer Deserizer = Config.getdeserializer (clazz);            if (Deserizer instanceof javabeandeserializer) {javabeandeser = (javabeandeserializer) Deserizer; } if (Javabeandeser = = null) {throw new Jsonexception ("Can not get Javabeandese            Rializer ");        } return (T) javabeandeser.createinstance (map, config);        } catch (Exception e) {throw new Jsonexception (E.getmessage (), E); }    }

Simply smoothed over, see the code in the yellow part of the code, it is to use the principle of reflection to obtain JavaBean.

As below, the demo for Gson:

1  PackageCn.code.gson;2 3 ImportJava.io.*;4 5 ImportJava.util.Map;6 7 ImportCom.google.gson.Gson;8 ImportCom.google.gson.GsonBuilder;9 Ten ImportCn.code.entity.Person; One  A /** - * Created by ZQ on 2017/6/16. -  */ the  Public classGsontest { -  -     /** -      * @paramargs main function parameter +      */ -      Public Static voidMain (string[] args) { +Gson Gson =NewGsonbuilder (). Create (); A  atGson.tojson ("Hello", System.out); -Gson.tojson ("123", System.out); - System.out.println (); -  - //Try (writer writer = new FileWriter ("D:\\gson.txt")) { - //Gson.tojson ("Hello", writer); in //Gson.tojson ("123", writer); - //} catch (IOException e) { to //e.printstacktrace (); + //      } -FileInputStream FileInputStream =NULL; the  *         Try { $FileInputStream =NewFileInputStream ("D:\\gson.txt");Panax Notoginseng}Catch(FileNotFoundException e) { - e.printstacktrace (); the         } +  APerson person =Getjavabean (fileinputstream); the  + System.out.println (person); -     } $  $     /** -      * -      * @paramFileInputStream Returning Java classes based on the attachment byte stream the      * @return -      */Wuyi      Public StaticPerson Getjavabean (FileInputStream fileinputstream) { theGson Gson =NewGsonbuilder (). Create (); -Person person =NULL; Wu  -         Try(Reader reader =NewInputStreamReader (FileInputStream)) { Aboutperson = Gson.fromjson (reader, person.class); $}Catch(FileNotFoundException e) { - e.printstacktrace (); -}Catch(IOException e) { - e.printstacktrace (); A         } +  the         returnPerson ; -     } $ } the  the  the //~ Formatted by jindent---http://www.jindent.com
View Code

Gson and Fastjson convert JSON objects to JavaBean simple controls

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.