The Open Event project uses JSON format for transferring event information like tracks, sessions, microlocations and other. The event exported in the zip format from the Open Event server also contains the data in JSON format. The Open Event Android application uses this JSON data. Before we use this data in the app, we have to parse the data to get Java objects that can be used for populating views. Deserialization is the process of converting JSON data to Java objects. In this post I explain how to deserialize JSON data using Jackson.
1. Add dependency
In order to use Jackson in your app add following dependencies in your app module’s build.gradle file.
2. Define entity model of data
In the Open Event Android we have so many models like event, session, track, microlocation, speaker etc. Here i am only defining track model because of it’s simplicity and less complexity.
Here if the property name is same as json attribute key then no need to add JsonProperty annotation like we have done for id, name color property. But if property name is different from json attribute key then it is necessary to add JsonProperty annotation.
3. Create sample JSON data
Let’s create sample JSON format data we want to deserialize.
4. Deserialize using ObjectMapper
ObjectMapper is Jackson serializer/deserializer. ObjectMapper’s readValue() method is used for simple deserialization. It takes two parameters one is JSON data we want to deserialize and second is Model entity class. Create an ObjectMapper object and initialize it.
Now create a Model entity object and initialize it with deserialized data from ObjectMapper’s readValue() method.
So we have converted JSON data into the Java object.
Jackson is very powerful library for JSON serialization and deserialization. To learn more about Jackson features follow the links given below.
- Jackson-databind: https://github.com/FasterXML/jackson-databind
- Jackson wiki: http://wiki.fasterxml.com/JacksonInFiveMinutes
- Tutorial: http://tutorials.jenkov.com/java-json/jackson-installation.html