简体   繁体   中英

parsing nested json using retrofit in android?

How to parse a JSON response using retrofit which looks like this, any help would be greatly appreciated, been stuck with this for a while now.

Update : Below is the code i have tried so far but i am not able to get the data and also i am not able to figure out what is wrong with it, jsonschema2pojo gave me two java classes and that's what i have used in my code. As per my understanding i am supposed to use those two java classes and pass my baseurl as well as endpoint and then calling them in my activity. I have followed the procedures correctly i suppose but have not been successful in retrieving the data so far.

{
"status": "success",
"data": [
    {
    "id": "1",
    "employee_name": "Tiger Nixon",
    "employee_salary": "320800",
    "employee_age": "61",
    "profile_image": ""
    },
    ....
    ]
}

MainActivity.java

private ArrayList<Datum> results;
private EmployeeAdapter employeeAdapter;
private RecyclerView recyclerView;

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

    getEmployees();
}

private void getEmployees() {

    GetEmployeeData getCountryDataService = RetrofitInstance.getService();

    Call<Info> call = getCountryDataService.getResults();

    call.enqueue(new Callback<Info>() {
        @Override
        public void onResponse(Call<Info> call, Response<Info> response) {

            Info info = response.body();

            if (info != null && info.getData() != null) {

                results = (ArrayList<Datum>) info.getData();

                viewData();

            }
        }

        @Override
        public void onFailure(Call<Info> call, Throwable t) {

            Toast.makeText(MainActivity.this, "Failed", Toast.LENGTH_SHORT).show();

        }
    });

}

private void viewData() {

    recyclerView = (RecyclerView) findViewById(R.id.rv_countries_list);
    employeeAdapter = new EmployeeAdapter(results);
    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setAdapter(employeeAdapter);

}

}

Datum.java

@SerializedName("id")
@Expose
private String id;

@SerializedName("employee_name")
@Expose
private String employeeName;


@SerializedName("employee_salary")
@Expose
private String employeeSalary;


@SerializedName("employee_age")
@Expose
private String employeeAge;


@SerializedName("profile_image")
@Expose
private String profileImage;

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getEmployeeName() {
    return employeeName;
}

public void setEmployeeName(String employeeName) {
    this.employeeName = employeeName;
}

public String getEmployeeSalary() {
    return employeeSalary;
}

public void setEmployeeSalary(String employeeSalary) {
    this.employeeSalary = employeeSalary;
}

public String getEmployeeAge() {
    return employeeAge;
}

public void setEmployeeAge(String employeeAge) {
    this.employeeAge = employeeAge;
}

public String getProfileImage() {
    return profileImage;
}

public void setProfileImage(String profileImage) {
    this.profileImage = profileImage;
}

Info.java

@SerializedName("status")
@Expose
private String status;


@SerializedName("data")
@Expose
private List<Datum> data = null;

public String getStatus() {
    return status;
}

public void setStatus(String status) {
    this.status = status;
}

public List<Datum> getData() {
    return data;
}

public void setData(List<Datum> data) {
    this.data = data;
}

Then the interface i am using is this

GetEmployeeData.java

@GET("employees")
Call<Info> getResults();

}

RetrofitInstance.java

private static Retrofit retrofit = null; private static String BASE_URL = " http://dummy.restapiexample.com/api/v1/ ";

public static GetEmployeeData getService() {


    if (retrofit == null) {

        retrofit = new Retrofit
                .Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }


    return retrofit.create(GetEmployeeData.class);
}

Here would be an example how to create a model class. I am doing it in Kotlin , but I'm sure you can convert it to Java easily.

import com.google.gson.annotations.SerializedName

data class EmployeeDTO(
   @SerializedName("id")
   var id: Int,
   @SerializedName("employee_name")
   var name: String,
   @SerializedName("employee_salary")
   var salary: Int,
   @SerializedName("employee_age")
   var age: Int, 
   @SerializedName("profile_image")
   var image: Boolean
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM