Compile your own json parsing tool 2
For a while, this is the second article of my json tool. It has been a while before the first article "write your own json parsing tool 1. There are many reasons for this period. I am lazy, busy with other jobs, and have encountered many details I have never thought. Now it has been basically written and can be used, but there are many restrictions, or the level is not enough. When the right is for reference to new scholars, it is estimated that it will be sprayed. This is the first complete placement. The code structure is not very clear and will be refactored later.
In addition to jdk, this tool does not rely on other third-party packages. The most important class of JSONUtil uses a lot of reflection, which is not frequently used. Others, such as JSONException, Person, and Phone, provide support for them, which is very simple.
How to Use JSONUtil:
The main four static methods can be used to implement conversion between json and Java built-in objects. The conversion between json and custom javaBean is limited to individual levels, and the conversion and object are limited. Javadoc description
Generate Java doc for the entire package
Some test code and effects:
(There are several test methods. Here we test the conversion of Javabean to json and then the conversion from json to javabean)
Person p = new Person (KJ405891, MUMU-XCJ, 23); Phone phone1 = new Phone (CN-HW-20141230001, glory 5, 1999.9); Phone phone2 = new Phone (CN-MZ-20141230001, meizu MX9, 888.0); p. addPhone (phone1); p. addPhone (phone2); try {// parse personString json2 = JSONUtil. beanToJson (p); System. out. println (json2); Person p4 = JSONUtil. jsonToBean (json2, Person. class); System. out. println (his name: + p4.getName () +, his age: + p4.getAge () +, his first phone brand: + p4.getPhonelist (). get (0 ). getBrand () +, price: + p4.getPhonelist (). get (0 ). getPrice ();} catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace ();}
Console:
// Output 1
// Output 2
Future optimization plan:
1. refactor the code to make the code module clearer.
2. Added support for various types, fixed bugs, and made tools more practical.