JSON is very popular with JavaScript and front-end developers because of the native exchange with JavaScript and simplify of JSON based web services. JSON is also growing in popularity as a data exchange and storage solution. JSON avoids the complexity and verbose syntax of XML while still preserving rich data structures.
Today, most utilities and libraries that read or write JSON are often customized, proprietary salutations or are based on XML serialization making them difficult to maintain, support and enhance. The goal of J2J is simply the generation of JSON from Java and mapping exiting JSON back again to native Java objects.
Key Elements:
The 5 key components of J2J are Java 3 annotations; @SimpleJsonObject, @JsonElement, @JsonMapping and 2 Java classes JsonReader and JsonWriter.
@SimpleJsonObject is used to identify java classes that will be used to generate and map JSON.
@JsonElement is used to identify and custom name fields between Java and JSON.
@JsonMapping is used in advanced cases where custom logic or processing needs to be done before the final JSON is generated or when mapping JSON to complex objects.
JsonReader check that the JSON is valid and maps it to your java objects.
JsonWriter takes in annotated java objects and based generates valid JSON.
Example 1.1: Generating JSON from Java
The first step in creating JSON is to annotate the java classes that will be used to generate the data. In this example identify that the Phone object with export JSON by adding the annotation @SimpleJsonObject to the the java class Phone.
At this point we use JsonWriter to generate JSON based on the existing getters. Setting the property values:
Phone phone = new Phone();
phone.setType("fax");
phone.setNumber("646 555-4567");
String jsonString = new JsonWriter(user).toString();
If the user objects properties have been populated with data JsonWriter will generate a the following JSON:
{"type":"fax","number":"646 555-4567"}
Example 1l2: Generating Named JSON elements:
The above example assumes that the property names are identical to the JSON names and that all the properties will be generated as part of the final JSON. However when the desired JSON does not match the class structure identically the @JsonElement can be used. Adding @JsonElement tell JsonWriter to only generate output from properties that have been annotated. Removing an annotation will also remove it from the output. The @JsonElement(name = "phone_number") will name the element other than the property name.
For example, the adding @JsonElement(name = "phone_number") the the getNumber() property:
J2J has the ability to navigate down an the object graph picking up all sub object that have also been marked with the @SimpleJsonObject annotation. The same rules for @JsonElement apply to the sub-objects.
For this example we will use 3 java object; User, Address and Phone. The User object will contain Address as a sub-object and previous Phone object as an array of Phones
As default JsonWriter will generated compressed or minified JSON but JsonWriter can also create long from or pretty prettied JSON. Adding JsonWriter.PRETTY to the toString() method:
String jsonString = new JsonWriter(user).toString(JsonWriter.PRETTY);
Example 1.4: Advanced processing:
When the expected JSON does not map the Java class properties or if the class has complex data processing or other requirements you can add @JsonMapping attribute to fine tune the resulting JSON. The method that is annotated with @JsonMapping takes one parameter, (JsonMap map).
JsonReader take the class definition and the JSON string as parameters mapping the data to a User object with the following command:
User user = (User) new JsonReader(User.class, son).toObject();
Example 2.2: Complex JSON
When the JSON represent a complex data structure it can be mapped to a similar Java object structure using JsonReader. To tell JsonReader how to map data to Java object you simply need to add path to the @SimpleJsonObject annotation like @SimpleJsonObject(path = "//…").
The sample JSON we will use is:
{"address":{"address":"3912 West end drive","state":"Hong Kong","city":"Happy Valley"},"screen_name":"John Johnson","id":808,"user_id":"dork1","email_address":"john@nowhere.com","phone_numbers":[{"phone_type":"home","phone_number":"(555) 321-1234"},{"phone_type":"cell","phone_number":"(555) 888-1234"},{"phone_type":"work","phone_number":"(555) 999-1234"}]}
The Address object maps to //user/address and the PhoneNumber object maps to //user/phone_numbers.
Next we need to tell JsonWriter where those object are found in our project. This is done using JsonClassScanner. takes in one parameter, a string defining the root package. We are now ready to map the JSON to the Java object:
// Read the entire contents of sample.txtStringjson=FileUtils.readFileToString(file);// For shake of this example we show the file content here.JsonClassScannerscanner=newJsonClassScanner("com.zenworld");// map the object.Objectactual=newJsonReader(User.class,scanner,json).toObject();
Conclusion
Please explore the examples included with J2J to become more familiar advanced features of the library. Let us know your successes and uses of JsonWriter and JsonReader. We also welcome any suggestions for improvement, bug or change requests that you may have.
Welcome to J2J Tutorial
J2J Tutorial
(est. 1 hour)
About J2J
JSON is very popular with JavaScript and front-end developers because of the native exchange with JavaScript and simplify of JSON based web services. JSON is also growing in popularity as a data exchange and storage solution. JSON avoids the complexity and verbose syntax of XML while still preserving rich data structures.
Today, most utilities and libraries that read or write JSON are often customized, proprietary salutations or are based on XML serialization making them difficult to maintain, support and enhance. The goal of J2J is simply the generation of JSON from Java and mapping exiting JSON back again to native Java objects.
Key Elements:
The 5 key components of J2J are Java 3 annotations; @SimpleJsonObject, @JsonElement, @JsonMapping and 2 Java classes JsonReader and JsonWriter.
@SimpleJsonObject is used to identify java classes that will be used to generate and map JSON.
@JsonElement is used to identify and custom name fields between Java and JSON.
@JsonMapping is used in advanced cases where custom logic or processing needs to be done before the final JSON is generated or when mapping JSON to complex objects.
JsonReader check that the JSON is valid and maps it to your java objects.
JsonWriter takes in annotated java objects and based generates valid JSON.
Example 1.1: Generating JSON from Java
The first step in creating JSON is to annotate the java classes that will be used to generate the data. In this example identify that the Phone object with export JSON by adding the annotation @SimpleJsonObject to the the java class Phone.
At this point we use JsonWriter to generate JSON based on the existing getters. Setting the property values:
If the user objects properties have been populated with data JsonWriter will generate a the following JSON:
Example 1l2: Generating Named JSON elements:
The above example assumes that the property names are identical to the JSON names and that all the properties will be generated as part of the final JSON. However when the desired JSON does not match the class structure identically the @JsonElement can be used. Adding @JsonElement tell JsonWriter to only generate output from properties that have been annotated. Removing an annotation will also remove it from the output. The @JsonElement(name = "phone_number") will name the element other than the property name.
For example, the adding @JsonElement(name = "phone_number") the the getNumber() property:
will produce:
Example 1.3: Complex Java Objects:
J2J has the ability to navigate down an the object graph picking up all sub object that have also been marked with the @SimpleJsonObject annotation. The same rules for @JsonElement apply to the sub-objects.
For this example we will use 3 java object; User, Address and Phone. The User object will contain Address as a sub-object and previous Phone object as an array of Phones
User Object
Address Object
Phone Object
Next we need a simple Driver class to show how it all ties together.
Running the Driver class will generate the following JSON output
As default JsonWriter will generated compressed or minified JSON but JsonWriter can also create long from or pretty prettied JSON. Adding JsonWriter.PRETTY to the toString() method:
will create the following pretty printed output:
Example 1.4: Advanced processing:
When the expected JSON does not map the Java class properties or if the class has complex data processing or other requirements you can add @JsonMapping attribute to fine tune the resulting JSON. The method that is annotated with @JsonMapping takes one parameter, (JsonMap map).
for example the following java class
produces the following JSON:
Part 2: JsonReader
JsonReader is used similarly as JsonWriter, but takes in a JSON string and maps it to a Java objects.
Example 2.1: mapping a JSON string to Java
given the following JSON string
{"name":"Bob Doe","username":"bobby","email":"bob@doe.org"}
JsonReader take the class definition and the JSON string as parameters mapping the data to a User object with the following command:
User user = (User) new JsonReader(User.class, son).toObject();
Example 2.2: Complex JSON
When the JSON represent a complex data structure it can be mapped to a similar Java object structure using JsonReader. To tell JsonReader how to map data to Java object you simply need to add path to the @SimpleJsonObject annotation like @SimpleJsonObject(path = "//…").
The sample JSON we will use is:
The Address object maps to //user/address and the PhoneNumber object maps to //user/phone_numbers.
Next we need to tell JsonWriter where those object are found in our project. This is done using JsonClassScanner. takes in one parameter, a string defining the root package. We are now ready to map the JSON to the Java object:
Conclusion
Please explore the examples included with J2J to become more familiar advanced features of the library. Let us know your successes and uses of JsonWriter and JsonReader. We also welcome any suggestions for improvement, bug or change requests that you may have.
Enjoy.
References
http://www.json.org
http://en.wikipedia.org/wiki/JSON
http://en.wikipedia.org/wiki/Comparison_of_data_serialization_formats
http://www.ietf.org/rfc/rfc4627.txt