jujka
jujka

Reputation: 1217

How to work with JSON: correct way

What is the best way to handle JSON in Android development?

There should be a somehow elegant way, I'm sure this question bothers a lot of beginners.

Upvotes: 0

Views: 87

Answers (1)

jujka
jujka

Reputation: 1217

Tools:

  1. Do use POJO for your classes, which are intended to be serialized: http://www.jsonschema2pojo.org
  2. Do use GSON (of Jackson) for JSON serialization / deserialization https://github.com/google/gson

Here's how amazingly it works:

Create JSON representation of your class:

{
   "name": "Jack",
   "tel": "+79998764521",
   "address": "Liberty St, 8 apt. 87"
}

Use POJO generator to create a class for you. Preferably, make sure that:

  • Source type: JSON
  • Annotation style: GSON

Employee.java

package com.bidwingames.app.bidrush.model;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;

import javax.annotation.Generated;

@Generated("org.jsonschema2pojo")
public class Employee {

    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("tel")
    @Expose
    private String tel;
    @SerializedName("address")
    @Expose
    private String address;

    /**
     * No args constructor for use in serialization
     *
     */
    public Employee() {
    }

    /**
     *
     * @param address
     * @param tel
     * @param name
     */
    public Employee(String name, String tel, String address) {
        this.name = name;
        this.tel = tel;
        this.address = address;
    }

    /**
     *
     * @return
     * The name
     */
    public String getName() {
        return name;
    }

    /**
     *
     * @param name
     * The name
     */
    public void setName(String name) {
        this.name = name;
    }

    public Employee withName(String name) {
        this.name = name;
        return this;
    }

    /**
     *
     * @return
     * The tel
     */
    public String getTel() {
        return tel;
    }

    /**
     *
     * @param tel
     * The tel
     */
    public void setTel(String tel) {
        this.tel = tel;
    }

    public Employee withTel(String tel) {
        this.tel = tel;
        return this;
    }

    /**
     *
     * @return
     * The address
     */
    public String getAddress() {
        return address;
    }

    /**
     *
     * @param address
     * The address
     */
    public void setAddress(String address) {
        this.address = address;
    }

    public Employee withAddress(String address) {
        this.address = address;
        return this;
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder().append(name).append(tel).append(address).toHashCode();
    }

    @Override
    public boolean equals(Object other) {
        if (other == this) {
            return true;
        }
        if ((other instanceof Employee) == false) {
            return false;
        }
        Employee rhs = ((Employee) other);
        return new EqualsBuilder().append(name, rhs.name).append(tel, rhs.tel).append(address, rhs.address).isEquals();
    }

}

Now, everything is done for you: getters and setters, constructor, builder and .equals methods (which sometimes is really important)

Usage:

Now, let's imagine that we want to deserialize the JSON that we have used to build our class to an object. Simple enough:

String JSON = "{\n" +
                "\t\"name\": \"Jack\",\n" +
                "\t\"tel\": \"+79998764521\",\n" +
                "\t\"address\": \"Liberty St, 8 apt. 87\"\n" +
                "}";

// Deserialize
Employee employee = new Gson().fromJson(JSON, Employee.class);

// Serialize
String serializedJSON = new Gson().toJson(employee);

And this is it! Simple and elegant enough! Plus, using POJO gives you quite an advantage in using things like Retrofit, meaning that your models are ConverterFactory-ready: GsonConverterFactory will automatically prepare all the data for the call end etc.

Upvotes: 1

Related Questions