2. 一个示例
来一个简单示例感受一下(所有代码可在源码包src\test\java\xyz\calvinwilliams\okjson
里找到)
2.1. 编写JSON文件
demo.json
{
"userName" : "Calvin" ,
"email" : "calvinwilliams@163.com" ,
"userExtInfo" : {
"gender" : "M" ,
"age" : 30 ,
"address" : "I won't tell you"
} ,
"interestGroupList" : [
"Programing", "Playing game", "Reading", "Sleeping"
] ,
"borrowDetailList" : [
{
"bookName" : "Thinking in JAVA" ,
"author" : "Bruce Eckel" ,
"borrowDate" : "2014-01-02" ,
"borrowTime" : "17:30:00"
} ,
{
"bookName" : "Thinking in C++" ,
"author" : "Bruce Eckel too" ,
"borrowDate" : "2014-02-04" ,
"borrowTime" : "17:35:00"
} ,
{
"bookName" : "Thinking in okjson" ,
"author" : "It's me !!!" ,
"borrowDate" : "2014-03-06" ,
"borrowTime" : "17:40:00"
}
]
}
2.2. 编写实体类
DemoUserClass.java
package xyz.calvinwilliams.okjson;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.LinkedList;
public class DemoUserClass {
String userName ;
String email ;
UserExtInfo userExtInfo ;
LinkedList<String> interestGroupList ;
LinkedList<BorrowDetail> borrowDetailList ;
}
class UserExtInfo {
String gender ;
int age ;
String address ;
}
class BorrowDetail {
String bookName ;
String author ;
@OkJsonDateTimeFormatter(format="yyyy-MM-dd")
LocalDate borrowDate ;
@OkJsonDateTimeFormatter(format="HH:mm:ss")
LocalTime borrowTime ;
}
2.3. 编写示例代码
读入JSON文件,映射所有字段数据到实体类属性中去
package xyz.calvinwilliams.okjson;
import java.time.format.DateTimeFormatter;
public class Demo {
public static void printDemoUser( DemoUserClass demoUser ) {
...
}
public static void main(String[] args) {
DemoUserClass demoUser = new DemoUserClass() ;
System.out.println( "OKJSON.stringToObject ..." );
demoUser = OKJSON.fileToObject( "demo.json", DemoUserClass.class, OKJSON.OKJSON_OTIONS_DIRECT_ACCESS_PROPERTY_ENABLE ) ;
if( demoUser == null ) {
System.out.println( "OKJSON.stringToObject failed["+OKJSON.getErrorCode()+"]["+OKJSON.getErrorDesc()+"]" );
return;
} else {
System.out.println( "OKJSON.stringToObject ok" );
printDemoUser( demoUser );
}
}
}
调用一个静态方法就能把JSON所有字段数据都映射到实体类属性中去,是不是很简单。
我的其它开源产品都用它装载配置文件,小巧、高效、灵活。
当前内容版权归 calvinwilliams 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 calvinwilliams .