Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetching json object and array from retrofit

I want to fetch json from [this link][1]: https://api.myjson.com/bins/38ln5 using retrofit

sample json is

{
  "students": [
    {
      "id": "1",
      "name": "Larzobispa"
    },
    {
      "id": "2",
      "name": "La Cibeles"
    }
  ]
}

Please explain details how to do that. Thanks a lot, guys!

like image 714
Emma Avatar asked Jan 05 '16 19:01

Emma


2 Answers

Retrofit will automatically parse JSON Object as well JSON Array.

@GET("/[email protected]")
public void responseString(Callback<Student> response);

your model class looks like:

public class Student{
private ArrayList<StudentInfo> studentList = new ArrayList<>();
     //getter and setters
}

public class StudentInfo{
    private String id;
    private String name;
    //getters and setters
}

Then in response:

@Override
public void onResponse(Response<Student> response, Retrofit retrofit) {
    if (response.isSuccess()) {
        Student student = response.body;
        Log.e("Student name", student.getStudent().get(0).getName()); // do whatever you want
    }else{
        // get response.errorBody()
    }
}
like image 173
Vishal Raj Avatar answered Oct 02 '22 04:10

Vishal Raj


You can access both JSONArray and JSONObject using retrofit 2.0 in android. Here you want to access JSONArray using retrofit for which you should do following:

Interface Class:



package com.androidtutorialpoint.retrofitandroid;
import java.util.List;

import retrofit.Call;
import retrofit.http.GET;

/**
 * Created by navneet on 4/6/16.
 */
public interface RetrofitArrayAPI {

    /*
     * Retrofit get annotation with our URL
     * And our method that will return us details of student.
    */
    @GET("api/RetrofitAndroidArrayResponse")
    Call> getStudentDetails();

}


Above is the interface. Now to display JSONArray data on your smartphone screen call following function:



    void getRetrofitArray() {
    Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        RetrofitArrayAPI service = retrofit.create(RetrofitArrayAPI.class);

        Call> call = service.getStudentDetails();

        call.enqueue(new Callback>() {

         @Override
            public void onResponse(Response> response, Retrofit retrofit) {

              try {
                List StudentData = response.body();
                for (int i = 0; i<StudentData.size(); i++) {
                  if (i == 0) {
                            text_id_1.setText("StudentId  :  " + StudentData.get(i).getStudentId());
                            text_name_1.setText("StudentName  :  " + StudentData.get(i).getStudentName());
                            text_marks_1.setText("StudentMarks  : " + StudentData.get(i).getStudentMarks());
                  } else if (i == 1) {
                            text_id_2.setText("StudentId  :  " + StudentData.get(i).getStudentId());
                            text_name_2.setText("StudentName  :  " + StudentData.get(i).getStudentName());
                            text_marks_2.setText("StudentMarks  : " + StudentData.get(i).getStudentMarks());
                  }
                }
              } catch (Exception e) {
                    Log.d("onResponse", "There is an error");
                    e.printStackTrace();
              } 
           }

           @Override
           public void onFailure(Throwable t) {
                Log.d("onFailure", t.toString());
           }

        });
    }


My POJO Class was following:



    package com.androidtutorialpoint.retrofitandroid;

public class Student {

    //Variables that are in our json
    private int StudentId;
    private String StudentName;
    private String StudentMarks;
    private int inStock;

    //Getters and setters
    public int getStudentId() {
        return StudentId;
    }

    public void setStudentId(int bookId) {
        this.StudentId = StudentId;
    }

    public String getStudentName() {
        return StudentName;
    }

    public void setStudentName(String name) {
        this.StudentName = StudentName;
    }

    public String getStudentMarks() {
        return StudentMarks;
    }

    public void setStudentMarks(String price) {
        this.StudentMarks = StudentMarks;
    }

}


So in this way, you will be able to capture JSONArray from URL using Retrofit 2.0 and display that data on your screen.

I hope I am able to answer your query.

Credits: I read this tutorial on: AndroidTutorialPoint for Retrofit 2.0

like image 20
Navneet Goel Avatar answered Oct 02 '22 03:10

Navneet Goel