Nano is my light-weight xml/json binding framework, it is a light-weight alternative to JAXB. Both Nano and JAXB are annotation driven, you annotate your domain classes, then use Nano or JAXB to convert Java POJO to/from XML.Two highlights of Nano are :
- Tailored for Android platform.
- Support both xml and json binding.
In this tutorial, I will show you simple usage of Nano in normal Java environment, in later posts, I will show you how to use Nano on Androd platform.
Basic concepts:
- Marshalling or Serialization - Convert a Java object into a Xml or Json content.
- Unmarshalling or Deserialization - Convert Xml or Json content to a Java object.
Prerequisite:
- JDK 1.6 or above
- Nano 0.6.1 or above
Working with Nano is easy, just annotate your domain class with Nano annotations, later use nanoWriter.write() or nanoReader.read() to do the object / Xml(or Json) conversion.
1. Nano Dependency
Latest Nano can be downloaded by following link here, extract the zip file, and put all 3 jars in lib folder on your project classpath.
Note:
On normal Java platform, Nano depends on Kxml and org.json library, however, on Android, Nano has no such dependency, since Kxml and org.json are built in Android Platform.
2. Nano Annotation
For object that needs to be converted to / from XML file, it has to be annotated with Nano annotations. The annotations are pretty self-explanatory, see sample below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
|
On class level, RootElement(optional) annotation indicates that this class is Nano bindable, on field level, Element annotation indicates that this field maps to an Xml element, Attribute annotation indicates that this filed maps to an Xml attribute.
Note
field level annotations can only be used on fields(private is ok), not on getter or setter methods.
3. Convert Object to Xml or Json
Instantiate an object, get an Xml or Json writer instance from NanoFactory class, then write the object to output(file, console or plain string).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
|
Output
1 2 3 4 5 6 7 8 |
|
4. Convert XML or JSON back to Object
Get an Xml or Json reader instance from NanoFactory class, then read content(has just been written above) back into object instance.
Note that when you read back, you need to explictly tell Nano the target class name.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
Output
1 2 3 4 |
|
5. Now Your Turn
The usage of Nano can’t be simpler, now it’s your turn to try Nano framework, if necessary, you can find the whole source of this tutorial here.