JavaSON - Java對象與JSON數據相互轉換的Java類庫

jopen 8年前發布 | 28K 次閱讀 JavaSON Java開發

JavaSON

Synopsis

JavaSON是一個非常小的Java類庫能夠輕松實現Java對象與JSON數據格式的相互轉換,使用Java反射包實現。

Installation

Download the following .jar file and add it to your Java project's build path:

javason.jar

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.

Complete testing code can be found here

Format 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

項目地址: https://github.com/avikj/JavaSON

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!