JavaSON - Java对象与JSON数据相互转换的Java类库
jopen
9年前
JavaSON
Synopsis
JavaSON是一个非常小的Java类库能够轻松实现Java对象与JSON数据格式的相互转换,使用Java反射包实现。
Installation
Download the following .jar file and add it to your Java project's build path:
You can then import the converter and exception classes.
import co.avikj.JavaSON.JavaSONConverter; import co.avikj.JavaSON.JavaSONException;
Code Example
Converting to JSON
Animal myCat = new Animal("cat", "Amber", 4); Person me = new Person("Avik Jain", 15, 4.0, myCat, new Point(1, 2)); JSONObject jsonMe = JavaSONConverter.toJSONObject(me);
'jsonMe' now stores the following JSON data:
{ "name": "Avik Jain", "gpa": 4, "location": { "x": 1, "y": 2, "class": "co.avikj.JavaSON.demo.Point" }, "class": "co.avikj.JavaSON.demo.Person", "age": 15, "pet": { "name": "Amber", "type": "cat", "class": "co.avikj.JavaSON.demo.Animal", "age": 4 } }
Converting to Java Object
JSONObject jsonMe2 = new JSONObject("{\"name\":\"Avik Jain\",\"gpa\":4,\"location\":{\"x\":1,\"y\":2,\"class\":\"co.avikj.JavaSON.demo.Point\"},\"class\":\"co.avikj.JavaSON.demo.Person\",\"age\":15,\"pet\":{\"name\":\"Amber\",\"type\":\"cat\",\"class\":\"co.avikj.JavaSON.demo.Animal\",\"age\":4}}"); Person me2 = JavaSONConverter.toJavaObject(jsonMe2)
The data in 'me2' is now identical to that in 'me' in the previous example.
here
Complete testing code can be foundFormat Requirements
Converting to JSON
- A field will be included in the JSON output if and only if the field has a public accessor method following the Java naming standard (getFieldName())
- The JSON data must not contain any arrays
Converting to Java Object
- JSON data must include an entry for "class" that stores the value of the Java class name for an object. This name is automatically included when a JSONObject is created using JavaSONConverter.toJSONObject().
- The Java class for the object must have a no-args constructor
- The fields included in the JSON data must have public mutator methods following the Java naming standard (setFieldName())
- The Java class must not include any array fields
Coming Soon
- Support for arrays when converting from JSON to Java Objects and vice-versa