okjson小巧、高效、灵活的 JSON 处理器
okjson - JAVA编写的小巧、高效、灵活的JSON处理器(JSON解析器+JSON生成器)
1. 概述
okjson是用JAVA编写的JSON处理器(JSON解析器+JSON生成器)。
它能帮助开发者把一段JSON文本中的数据映射到实体类中,或由一个实体类生成一段JSON文本。
它小巧,源码只有一个类文件和一个注解类文件,方便架构师嵌入到项目/框架中去。
它高效,比号称全世界最快的fastjson还要快。
它灵活,不对映射实体类有各种各样约束要求。
一个好工具就是简单、朴素的。
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🇲🇲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所有字段数据都映射到实体类属性中去,是不是很简单。
我的其它开源产品都用它装载配置文件,小巧、高效、灵活。
6. 关于本项目
欢迎使用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. 关于作者
厉华,左手C,右手JAVA,写过小到性能卓越方便快捷的日志库、HTTP解析器、日志采集器等,大到交易平台/中间件等,分布式系统实践者,容器技术专研者,目前在某城商行负责基础架构。
评论
