okjson小巧、高效、靈活的 JSON 處理器
okjson - JAVA編寫的小巧、高效、靈活的JSON處理器(JSON解析器+JSON生成器)
1. 概述
okjson是用JAVA編寫的JSON處理器(JSON解析器+JSON生成器)。
它能幫助開發(fā)者把一段JSON文本中的數(shù)據(jù)映射到實體類中,或由一個實體類生成一段JSON文本。
它小巧,源碼只有一個類文件和一個注解類文件,方便架構(gòu)師嵌入到項目/框架中去。
它高效,比號稱全世界最快的fastjson還要快。
它靈活,不對映射實體類有各種各樣約束要求。
一個好工具就是簡單、樸素的。
2. 一個示例
來一個簡單示例感受一下(所有代碼可在源碼包src\test\java\xyz\calvinwilliams\okjson里找到)
2.1. 編寫JSON文件
demo.json
{
"userName" : "Calvin" ,
"email" : "[email protected]" ,
"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????ss")
LocalTime borrowTime ;
}
2.3. 編寫示例代碼
讀入JSON文件,映射所有字段數(shù)據(jù)到實體類屬性中去
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 );
}
}
}
調(diào)用一個靜態(tài)方法就能把JSON所有字段數(shù)據(jù)都映射到實體類屬性中去,是不是很簡單。
我的其它開源產(chǎn)品都用它裝載配置文件,小巧、高效、靈活。
6. 關(guān)于本項目
歡迎使用okjson,如果你在使用中碰到了問題請告訴我,謝謝 ^_^
Apache Maven
<dependency> <groupId>xyz.calvinwilliams</groupId> <artifactId>okjson</artifactId> <version>0.0.9.0</version> </dependency>
Gradle Kotlin DSL
compile("xyz.calvinwilliams:okjson:0.0.9.0")
7. 關(guān)于作者
厲華,左手C,右手JAVA,寫過小到性能卓越方便快捷的日志庫、HTTP解析器、日志采集器等,大到交易平臺/中間件等,分布式系統(tǒng)實踐者,容器技術(shù)專研者,目前在某城商行負責(zé)基礎(chǔ)架構(gòu)。
評論
圖片
表情
