Backend Development 14 min read

Open-Source Java JSON Framework with Reflection-Based Serialization and Deserialization

This article introduces an open‑source Java JSON framework that uses recursive parsing and reflection to serialize and deserialize objects without third‑party libraries, supports generic and array types, and provides extensible features such as custom annotations, JsonPath, and HTML‑safe output.

Java Captain
Java Captain
Java Captain
Open-Source Java JSON Framework with Reflection-Based Serialization and Deserialization

The author presents a self‑written open‑source JSON framework for Java that parses JSON strings recursively, creates objects via reflection (requiring a no‑arg constructor), caches reflection data for performance, and handles complex generic, array, and mixed types, though it does not support Java 8+ date classes out of the box.

package test; import java.io.IOException; import java.lang.reflect.Type; import java.text.ParseException; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import june.zero.generic.ClassType; import june.zero.generic.TypeBuilder; import june.zero.json.JSON; import june.zero.json.reader.element.impl.JsonArray; import june.zero.json.reader.element.impl.JsonObject; import june.zero.json.reader.element.impl.JsonString; import june.zero.json.reader.parser.impl.JsonElementParser; import june.zero.json.reader.parser.impl.JsonObjectParser; import june.zero.json.writer.JsonWriter; public class Main { public static class User { public String name; public int age; public java.util.Date date; public int[] hobbys; public String jsonObjectData; public String jsonArrayData; public boolean flag; @Override public String toString() { return "User [age=" + age + ", date=" + date + ", flag=" + flag + ", hobbys=" + Arrays.toString(hobbys) + ", jsonArrayData=" + jsonArrayData + ", jsonObjectData=" + jsonObjectData + ", name=" + name + "]"; } } public static class Response { public int code; public String message; public T data; @Override public String toString() { return "Response [code=" + code + ", data=" + data + ", message=" + message + "]"; } } public static void main(String[] args) { testJsonFormat(); testDate(); testInsideJson(); testGenericType(); testCustom(); testJsonWrite(); testInOut(); testJsonObjectParser(); } public static void testJsonFormat() { System.out.println("=====testJsonFormat====="); //标准JSON格式 String json1 = "{\"name\":\"张三\",\"age\":33}"; User user1 = JSON.fromJSON(json1, User.class); System.out.println(user1.name);//张三 //单引号格式 String json2 = "{'name':'张三','age':33,'date':'2024-06-06 12:12:12','hobbys':[1,2,3]}"; User user2 = JSON.fromJSON(json2, User.class); System.out.println(user2.date);//2024-06-06 12:12:12.0 //没有引号格式,不建议使用 String json3 = "{name:张三,age:33,flag:true}"; User user3 = JSON.fromJSON(json3, User.class); System.out.println(user3.flag);//true } public static void testDate() { System.out.println("=====testDate====="); // java.util.Date日期格式 yyyy-MM-dd hh:mm:ss.SSS,yyyy-MM-dd hh:mm:ss,yyyy-MM-dd hh:mm,yyyy-MM-dd hh,yyyy-MM-dd,yyyy-MM,yyyy String dataString = "'2024-06-06 12:12'"; java.util.Date d0 = JSON.fromJSON(dataString, java.util.Date.class); System.out.println(d0);//2024-06-06 12:12:00.0 java.util.Calendar d1 = JSON.fromJSON(dataString, java.util.Calendar.class); System.out.println(d1); java.sql.Timestamp d11 = JSON.fromJSON(dataString, java.sql.Timestamp.class); System.out.println(d11); //java.sql.Date日期格式 yyyy-MM-dd,yyyy-MM,yyyy String dataString2 = "'2024-06'"; java.sql.Date d2 = JSON.fromJSON(dataString2, java.sql.Date.class); System.out.println(d2); //java.sql.Time日期格式 hh:mm:ss,hh:mm,hh String dataString3 = "'12:12'"; java.sql.Time d3 = JSON.fromJSON(dataString3, java.sql.Time.class); System.out.println(d3); } public static void testInsideJson() { System.out.println("=====testInsideJson====="); //JsonArray转String String json1 = "{'jsonArrayData':[1,2,3]}"; User user1 = JSON.fromJSON(json1, User.class); System.out.println(user1.jsonArrayData);//[1,2,3] //JsonObject转String String json2 = "{'jsonObjectData':{name:张三}}"; User user2 = JSON.fromJSON(json2, User.class); System.out.println(user2.jsonObjectData);//{name:张三} //内部JSON字符串转对象 Type listMapType = new TypeBuilder >>>() {}.getGenericType(); String json3 = "{'code':1,'message':'查询成功','data':'[{name:李四,age:44},{name:王五,age:55}]'}"; Response >> response4 = JSON.fromJSON(json3, listMapType); System.out.println(response4.data);//[{age=44, name=李四}, {age=55, name=王五}] } public static void testGenericType() { System.out.println("=====testGenericType====="); String json = "{'code':1,'message':'查询成功','data':[{'name':'李四','age':44},{'name':'王五','age':55}]}"; System.out.println("=====类型1======"); Type listUserType = new TypeBuilder >>() {}.getGenericType(); System.out.println(listUserType); Response > response1 = JSON.fromJSON(json, listUserType); System.out.println(response1.data.get(1).name);//王五 System.out.println("=====类型2======"); Type listMapType = new TypeBuilder >>>() {}.getGenericType(); System.out.println(listMapType); Response >> response2 = JSON.fromJSON(json, listMapType); System.out.println(response2.data.get(1).get("name"));//王五 System.out.println("=====类型3======"); Type stringType = new TypeBuilder >() {}.getGenericType(); System.out.println(stringType); Response response3 = JSON.fromJSON(json, stringType); System.out.println(response3.data);//[{'name':'李四','age':44},{'name':'王五','age':55}] } @SuppressWarnings("unchecked") public static void testCustom() { System.out.println("=====testCustom====="); //自定义处理 String json = "{'code':1,'message':'查询成功','data':[{'name':'李四','age':15},{'name':'王五','age':20}]}"; Type listUserType = new TypeBuilder >>() {}.getGenericType(); JsonElementParser parser = new JsonElementParser(){ @Override protected JsonArray getJsonArray() { return new JsonArray(){ @Override public boolean add(Object e) { if(e instanceof User){ User u = (User)e; if(u.age<18){ //过滤掉不满18岁的数据 return false; } } return super.add(e); } }; } }; Response > response = (Response >)parser.parse(json, listUserType); System.out.println(response.data); //对已有对象进行赋值解析 String json2 = "{'code':0,'data':null}"; Type listUserType2 = new TypeBuilder >>() {}.getGenericType(); final Response > response2 = new Response >(){}; response2.code = 1; response2.message = "查询失败"; JsonElementParser parser2 = new JsonElementParser(){ @Override protected JsonObject getJsonObject() { return new JsonObject(){ @Override public void setType(Type genericType) { super.setType(genericType); if(this.type == Response.class){ this.elementValue = response2; } } }; } }; parser2.parse(json2, listUserType2); System.out.println(response2); //功能扩展 String json3 = "'Thu Jun 12 12:12:12 CST 2024'"; JsonElementParser parser3 = new JsonElementParser(){ @Override protected JsonString getJsonString() { return new JsonString(){ @SuppressWarnings("deprecation") @Override public Object getElementValue() throws ParseException { //扩展更多日期解析方式 if(this.genericType==java.util.Date.class){ try{ //尝试使用java.util.Date自带的方法进行解析 return new java.util.Date(java.util.Date.parse(this.toString())); }catch(Exception e){ //格式错误 } } return super.getElementValue(); } }; } }; Object o = parser3.parse(json3, java.util.Date.class); System.out.println(o); } public static void testJsonWrite() { System.out.println("=====testJsonWrite====="); User obj = new User(); obj.name="张三"; System.out.println(JSON.toJSON(obj)); //自定义输出 JsonWriter writer = new JsonWriter(){ @Override protected void writeObject(Object obj) throws IOException { if(obj instanceof User){ User u = (User)obj; JsonObjectWriter jsonObjectWriter = getJsonObjectWriter(); jsonObjectWriter.start(); jsonObjectWriter.write("name1", u.name); jsonObjectWriter.end(); return; } super.writeObject(obj); } }; StringBuilder json = new StringBuilder(); writer.write(obj, json); System.out.println(json); } @SuppressWarnings("unchecked") public static void testInOut() { System.out.println("=====testInOut====="); Map data = new HashMap (); data.put("content", " "); //普通转义输出 StringBuilder out = new StringBuilder(); JsonWriter writer = new JsonWriter(); writer.write(data, out); System.out.println(out); //HTML安全转义输出 StringBuilder out2 = new StringBuilder(); JsonWriter writer2 = new JsonWriter(); writer2.ofHtmlSafeReplace(true); writer2.write(data, out2); System.out.println(out2); //支持普通转义解析 String json2 = "{'content':'\u003cscript\u003ealert(2)\u003c/script\u003e'}"; Map map = JSON.fromJSON(json2, Map.class); System.out.println(map.get("content")); } public static void testJsonObjectParser() { System.out.println("=====testJsonObjectParser====="); Response >> response = new Response >>(); response.message = "查询成功"; //JsonObject java对象赋值器 new JsonObjectParser().parse('{"code":1,"data":[{"name":"李四","age":15},{"name":"王五","age":20}]}', response, ClassType.LIST_MAP_STRING_OBJECT_TYPE); System.out.println(JSON.toJSON(response)); } }

The article also notes that the source code and JAR are available for download, encourages attribution when reusing, and warns that the library was tested on JDK 1.7 and may need adjustments for production environments.

JavareflectionSerializationJSONdeserializationOpenSource
Java Captain
Written by

Java Captain

Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.