Java parses objects into JSON format without plug-ins

Source: Internet
Author: User

A piece of parsing code written by myself:

Character effect after resolution:

{'Student ': {ID: 1, string:' This is a person ', address: 'changsha', {'human ': {ID: 1, type: 'Yellow race ', {'product': {ID: 1, name: 'iphone5', Description: 'product description', IMG: 'image', stock: 12, bidprice: 12.0, price: 3000.0, null, null, supplier: 'u.s. ', addtime: '2017-01-01 08:00:00. 1' }}{ 'LIST': {'student ': {ID: 1, string:' This is a person ', address: 'changsha', {'human ': {ID: 1, type: 'Yellow people', {'product': {ID: 1, name: 'iphone5', Description: 'product description', IMG: 'image', stock: 12, bidprice: 12.0, price: 3000.0, null, null, supplier: 'u.s. ', addtime: '2017-01-01 08:00:00. 1 '}},{ 'human': {ID: 1, type: 'Yellow people', {'product': {ID: 1, name: 'iphone5', description: 'product description', IMG: 'image', stock: 12, bidprice: 12.0, price: 3000.0, null, null, supplier: 'America ', addtime: '2017-01-01 08:00:00. 1 '}}

However, the number of child objects in the object's fields can be parsed using recursion.

When calling this class for parsing, use the packaging class for all bean fields; otherwise, an exception occurs.

Code Section:

Main parsing code:

Beanutil. Java

Package Org. dreamer. data. util; import Java. lang. reflect. field;/*** return all field values of this object * @ author Pan **/public class beanutil {/*** return the string of the current object */Public String tostring () {return getstring (this);}/*** returns the string of the specified object * @ Param object * @ return */Public String getstring (Object object) {If (Object = NULL) Return "null"; string STR = ""; STR + = "{'" + object. getclass (). getsimplename () + "': {"; Class Cl = object. getclass (); FIE LD [] fields = Cl. getdeclaredfields (); Boolean Sign = true; string S = ","; for (field: fields) {field. setaccessible (true); // set it to accessible // determine whether the field is an object if (sign) {S = ""; Sign = false;} else {S = ", ";}try {typecollection types = new typecollection (); boolean result = types. check (field. get (object); // if it is not a basic type, use recursion to find all sub-objects if (! Result) {STR + = S + getstring (field. Get (object); continue;} object value = jsonhelper. Check (field. Get (object ))? "'" + Field. get (object) + "'": field. get (object); STR + = S + field. getname () + ":" + value;} catch (exception e) {// todo auto-generated catch blocke. printstacktrace () ;}} STR + = "}"; return STR ;}}

JSON helper class:

Jsonhelper. Java

Package Org. dreamer. data. util; import Java. SQL. timestamp; public class jsonhelper {/*** check whether the type is string or timestamp * @ Param object * @ return */public static Boolean check (Object object) {return object instanceof string | object instanceof timestamp ;}}

Jsonsupport. Java

This class is called. This class can parse objects and object arrays.

Package Org. dreamer. data. JSON; import Java. util. collection; import Org. dreamer. data. util. beanutil;/*** JSON parsing object, if the field type of the object is not the basic type *, recursive Parsing is called. * @ author Pan **/public class jsonsupport {/*** parses the object into a JSON string *@ param object * @ return */public static string parsestring (Object object) {// check whether the object inherits the beanutil class string superclass = object. getclass (). getsuperclass (). getcanonicalname (); beanutil = new beanutil (); // if the object has inherited the beanutil class, the tostring method of the object will be called directly. // beanutil has re-called tostring and so on. // you do not need to perform repeated operations if (beanutil. getclass (). getcanonicalname (). equals (superclass) {return object. tostring ();} return beanutil. getstring (object);}/*** parse a collection object * @ Param Collection * @ return */public static string parsecollection (Collection collection) {string STR = "{'LIST':"; Boolean Sign = true; string charstr = ","; for (Object object: Collection) {If (sign) {charstr = ""; Sign = false;} else {charstr = "," ;}str + = charstr + parsestring (object) ;}return STR + = "";}}

Typecollection. Java is very important because it is necessary to determine whether the parsed object is of the basic type. If it is of some basic data types, it will not be parsed.

Package Org. dreamer. data. util; import Java. lang. reflect. field; import Java. SQL. timestamp;/*** basic type set * @ author Pan **/public class typecollection {/*** basic data type package class */private integer; private double double1; private float float1; private long long1; private string; private character; private Boolean boolean1; private short short1; private timestamp; /*** check whether the object is of the basic data type * @ Param object * @ return */Public Boolean check (Object object) {If (Object = NULL) return false; // obtain the field set of the current class object field [] fields = This. getclass (). getdeclaredfields (); For (field: fields) {// set the field to access field. setaccessible (true); // obtain the field type to compare if (field. getType (). getname (). equals (object. getclass (). getname () {return true ;}} return false ;}}

It is very easy to parse into JSON, which is a little easier than the bloated plug-in on the Internet.

Below is a piece of code I tested:

Do not run it directly. An error is reported.

Package COM. domain; import Java. SQL. timestamp; import Java. util. arraylist; import Java. util. list; import Org. dreamer. data. JSON. jsonsupport; import Org. dreamer. data. util. beanutil; import Org. dreamer. data. util. typecollection; import COM. pan. action. product; import COM. pan. beans. user; public class jsontest {public static void main (string [] ARGs) throws exception {student = new student (); student. setaddress ("Changsha"); product Product = new product (); product. setaddtime (New timestamp (100); product. setbidprice (12d); product. setdescription ("product description"); product. setid (1); product. setimg ("image"); product. setname ("iphone5"); product. setprice (3000d); product. setstock (12); product. setsupplier ("us"); Human human = new human (); Human. setproduct (product); Human. setid (1); human. settype ("yellow"); student. sethuman (human); student. setid (1); student. setstring ("this is a person"); system. out. println (student. getclass (). getsuperclass (). getcanonicalname (); List list = new arraylist (); list. add (student); list. add (human); system. out. println (student); system. out. println (jsonsupport. parsecollection (list ));}}

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.