Java library to convert between JSON and Java annotations at runtime.
Leveraging Javanna to read and create annotations, and Gson to parse and write JSON documents, Javanna-Gson allows you to map JSON to Java annotations.
Javanna-Gson is on JCenter and Maven Central.
dependencies {
compile "com.athaydes.javanna:javanna-gson:1.0"
}
<dependency>
<groupId>com.athaydes.javanna</groupId>
<artifactId>javanna-gson</artifactId>
<version>1.0</version>
</dependency>
The whole library is one class: com.athaydes.javanna.gson.JavannaGson
.
It has a default constructor that does not take any arguments, but may also be created with a
provided Gson
instance.
Given a couple of Java annotation definitions such as the ones below:
@Retention( RetentionPolicy.RUNTIME )
@interface Server {
/**
* @return the name of this server.
*/
String name() default "-";
/**
* @return the port the server should listen to.
*/
int port() default 80;
/**
* @return the location of the Server log file.
*/
String logFile() default "/var/log/server.log";
WhiteLists whiteLists() default @WhiteLists;
}
@Retention( RetentionPolicy.RUNTIME )
@interface WhiteLists {
String[] ips() default { };
int[] ports() default { };
}
The following code will parse a JSON document into an instance of Server
:
Server server = javannaGson.parse( jsonString, Server.class );
The JSON document may look like the following:
{
"name": "Super Server",
"port": 43,
"whiteLists": {
"ips": [
"192.168.10.1",
"255.255.255.255"
],
"ports": [
60,
90
]
}
}
To write an annotation to JSON, do the following:
String json = javannaGson.toJson( annotation );
If you want to send it out over a Writer
or Appendable
:
javannaGson.toJson( server, writer );
Annotations have several properties that make them ideal to represent pure data:
- annotation instances are immutable.
- support for default values.
- no null anywhere, even within String arrays.
- no inheritance, only composition.
- no logic.
Also, annotations have no Collection or other custom types, mapping extremely well to JSON's types.
This limitation means you never need to worry about non-serializable types and TypeAdapter
s.