2. 一个示例

来一个简单示例感受一下(所有代码可在源码包src\test\java\xyz\calvinwilliams\okjson里找到)

2.1. 编写JSON文件

demo.json

  1. {
  2. "userName" : "Calvin" ,
  3. "email" : "calvinwilliams@163.com" ,
  4. "userExtInfo" : {
  5. "gender" : "M" ,
  6. "age" : 30 ,
  7. "address" : "I won't tell you"
  8. } ,
  9. "interestGroupList" : [
  10. "Programing", "Playing game", "Reading", "Sleeping"
  11. ] ,
  12. "borrowDetailList" : [
  13. {
  14. "bookName" : "Thinking in JAVA" ,
  15. "author" : "Bruce Eckel" ,
  16. "borrowDate" : "2014-01-02" ,
  17. "borrowTime" : "17:30:00"
  18. } ,
  19. {
  20. "bookName" : "Thinking in C++" ,
  21. "author" : "Bruce Eckel too" ,
  22. "borrowDate" : "2014-02-04" ,
  23. "borrowTime" : "17:35:00"
  24. } ,
  25. {
  26. "bookName" : "Thinking in okjson" ,
  27. "author" : "It's me !!!" ,
  28. "borrowDate" : "2014-03-06" ,
  29. "borrowTime" : "17:40:00"
  30. }
  31. ]
  32. }

2.2. 编写实体类

DemoUserClass.java

  1. package xyz.calvinwilliams.okjson;
  2. import java.time.LocalDate;
  3. import java.time.LocalTime;
  4. import java.util.LinkedList;
  5. public class DemoUserClass {
  6. String userName ;
  7. String email ;
  8. UserExtInfo userExtInfo ;
  9. LinkedList<String> interestGroupList ;
  10. LinkedList<BorrowDetail> borrowDetailList ;
  11. }
  12. class UserExtInfo {
  13. String gender ;
  14. int age ;
  15. String address ;
  16. }
  17. class BorrowDetail {
  18. String bookName ;
  19. String author ;
  20. @OkJsonDateTimeFormatter(format="yyyy-MM-dd")
  21. LocalDate borrowDate ;
  22. @OkJsonDateTimeFormatter(format="HH:mm:ss")
  23. LocalTime borrowTime ;
  24. }

2.3. 编写示例代码

读入JSON文件,映射所有字段数据到实体类属性中去

  1. package xyz.calvinwilliams.okjson;
  2. import java.time.format.DateTimeFormatter;
  3. public class Demo {
  4. public static void printDemoUser( DemoUserClass demoUser ) {
  5. ...
  6. }
  7. public static void main(String[] args) {
  8. DemoUserClass demoUser = new DemoUserClass() ;
  9. System.out.println( "OKJSON.stringToObject ..." );
  10. demoUser = OKJSON.fileToObject( "demo.json", DemoUserClass.class, OKJSON.OKJSON_OTIONS_DIRECT_ACCESS_PROPERTY_ENABLE ) ;
  11. if( demoUser == null ) {
  12. System.out.println( "OKJSON.stringToObject failed["+OKJSON.getErrorCode()+"]["+OKJSON.getErrorDesc()+"]" );
  13. return;
  14. } else {
  15. System.out.println( "OKJSON.stringToObject ok" );
  16. printDemoUser( demoUser );
  17. }
  18. }
  19. }

调用一个静态方法就能把JSON所有字段数据都映射到实体类属性中去,是不是很简单。

我的其它开源产品都用它装载配置文件,小巧、高效、灵活。