Fetching json object and array from retrofit

前端 未结 2 962
执念已碎
执念已碎 2021-01-12 20:21

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

sample json is

{
  \"students\": [
    {
      \"id\": \"         


        
相关标签:
2条回答
  • 2021-01-12 20:30

    Retrofit will automatically parse JSON Object as well JSON Array.

    @GET("/register?email=example@123.com")
    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()
        }
    }
    
    0 讨论(0)
  • 2021-01-12 20:30

    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

    0 讨论(0)
提交回复
热议问题