How to parse Json using GSON library in Android

In this android programming source code example, we are going to parse Json using GSON library in Android.

You can copy and adopt this source code example to your android project without reinventing the wheel.

Below is a step by step source code to parse Json using GSON library in Android.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:orientation="vertical" 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=".json.Json3"
    android:layout_margin="16dp">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="14sp"
        android:textColor="@color/colorAccent"
        android:id="@+id/text"/>

</LinearLayout>

MainActivity.java

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.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.List;

public class Json4 extends AppCompatActivity {

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

        TextView textView = findViewById(R.id.text);

        Gson gson = new Gson();
        String json = "[ \"Adam\", \"John\", \"Mary\" ]";

        Type type = new TypeToken<List<String>>(){}.getType();
        List<String> name = gson.fromJson(json, type);

        textView.setText(name.toString());
        Log.v("Names", name.toString());
    }
}

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