How to convert Json String to Java Object in Android

Imagine getting a responses object from a remote data source in Json String format and you want to convert this response String to a Java Object in your client application.

There are many ways to achieve this. In our case, we are going to use Gson Android library

This is a code example you can adopt in your project. Feel free to customize it to fit with your project requirements.

1. Add Gson Library as Dependency in build.gradle File

implementation 'com.google.code.gson:gson:2.8.5'

This is the current version of Gson library as at the time of this tutorial. Be aware that it might have changed now that you are access this tutorial. Always make sure you use the latest android library version.

2. Mock a simple Json String

//Mock json string from remote service
String json = "{'city': 'Lagos', 'country': 'Nigeria'}";

3. Create a Model Class

We will create a simple POJO class to map the properties from Json to the model class we have created

public class CountryModel {

    private String city;
    private String country;


    public CountryModel(String city, String country) {
        this.city = city;
        this.country = country;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }
}

4. Add TextView in Activity XML Layout File

Drag and drop a TextView to the activity_main.xmlfile. We are going to display the Java class object properties in this View.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/json_object_properties"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

MainActivity class

Create a Gson object and user the Gson object method fromJson to convert the Json Object String to a Java Class

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.inducesmile.androidjson.model.CountryModel;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();

    private Gson gson;
    private GsonBuilder gsonBuilder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        gsonBuilder = new GsonBuilder();
        gson = gsonBuilder.create();

        //Mock json string from remote service
        String json = "{'city': 'lagos', 'country': 'Nigeria'}";

        CountryModel countryModel = gson.fromJson(json, CountryModel.class);

        TextView displayJsonObject = (TextView)findViewById(R.id.json_object_properties);
        displayJsonObject.setText(String.format("Object properties - City: %s Country %s", countryModel.getCity(), countryModel.getCountry()));

        //Log Object properties
        Log.d(TAG, "Object properties - City: " + countryModel.getCity() + " Country " + countryModel.getCountry());

    }
}

If everything works for you, you will get a screen similar to what we have below.

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

 

Add a Comment