从改造中获取json对象和数组

时间:2016-01-05 19:31:49

标签: android retrofit2

我想从[this link] [1]中获取json:https://api.myjson.com/bins/38ln5使用改造

示例json是

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

请详细说明如何操作。 非常感谢,伙计们!

2 个答案:

答案 0 :(得分:7)

Retrofit将自动解析JSON Object以及JSON Array。

@GET("/register?email=example@123.com")
public void responseString(Callback<Student> response);

你的模型类看起来像:

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

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

然后回应:

@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()
    }
}

答案 1 :(得分:1)

您可以使用android中的retrofit 2.0访问JSONArray和JSONObject。在这里,您希望使用您应该执行以下操作的改造来访问JSONArray:

接口类:



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();

}


以上是界面。现在,要在智能手机屏幕上显示JSONArray数据,请执行以下功能:



    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());
           }

        });
    }


我的POJO课程如下:



    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;
    }

}


因此,通过这种方式,您将能够使用Retrofit 2.0从URL捕获JSONArray并在屏幕上显示该数据。

我希望我能够回答您的问题。

致谢:我阅读本教程: AndroidTutorialPoint for Retrofit 2.0