How to receive a Json array (“result”) with retrofit2

只谈情不闲聊 提交于 2021-02-07 20:39:19

问题


I know how to receive arrays when they are this type:

[
{
    "username": "luis",
    "job": "developer",
    "age": 23
}
]

my problem is when I must receive an array with a specific name like this:

{"result":[{"userid":"1","username":"Luis","job":"developer","age":"23"}]}

in this case I must receive the array above with the name "result" using retrofit2. Can anyone please help me I'm new at Retrofit.

This is what I have tried:

MainActivity

apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
       Call<List<Workers>> call = apiInterface.getWorkers();

       call.enqueue(new Callback<List<Workers>>() {
           @Override
           public void onResponse(Call<List<Workers>> call, Response<List<Workers>> response) {
               list=response.body();
               adapter = new WorkerAdapter(getApplicationContext(),list);
               recyclerView.setAdapter(adapter);


           }

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

           }
       });

ApiClient:

public class ApiClient {

    public static final String BASE_URL="http://192.168.31.206/test1_database/";
    public static Retrofit retrofit = null;

    public static Retrofit getApiClient(){

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

}

ApiInterface:

public interface ApiInterface {

    @GET("getAllUser.php")
    Call<List<Workers>> getWorkers();


}

my POJO or Workers class:

public class Workers {

    @SerializedName("username")
    String Name;
    @SerializedName("job")
    String Job;
    @SerializedName("age")
    int Age;

    public String getName() {
        return Name;
    }

    public String getJob() {
        return Job;
    }

    public int getAge() {
        return Age;
    }
} 

and finally my RecyclerAdpter:

public class WorkerAdapter extends RecyclerView.Adapter<WorkerAdapter.ViewHolder>{
    Context context;
    List<Workers> list;

    public WorkerAdapter(Context context,List<Workers> list) {
        this.context = context;
        this.list = list;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(context).inflate(R.layout.item_recycler,parent,false);
        ViewHolder holder = new ViewHolder(v);
        return holder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {

        holder.name.setText(list.get(position).getName());
        holder.job.setText(list.get(position).getJob());
        holder.age.setText(String.valueOf(list.get(position).getAge()));
    }

    @Override
    public int getItemCount() {
        return list.size();
    }


    public class ViewHolder extends RecyclerView.ViewHolder {

        TextView name, job, age;

        public ViewHolder(View itemView) {
            super(itemView);
            name= (TextView) itemView.findViewById(R.id.nametxt);
            job=(TextView) itemView.findViewById(R.id.jobtxt);
            age=(TextView) itemView.findViewById(R.id.agetxt);
        }
    }
}

I've been stuck for two days now and I still can't solve it. Please help!


回答1:


create a class model called Result and in Interface class write this code:

 @GET("your endpoint")
 Call<Result>getResult();

and in Result class write below code:

 @SerializedName("result") 
 private List<UserInfo> userInfo;

good luck.




回答2:


package com.example;

import java.util.List;

public class Example {

private List<Result> result = null;

public List<Result> getResult()
{
    return result;
}

public void setResult(List<Result> result)
{
    this.result = result;
}}



package com.example;


public class Result {

private String userid;
private String username;
private String job;
private String age;

public String getUserid()
{
    return userid;
}

public void setUserid(String userid)
{
    this.userid = userid;
}

public String getUsername()
{
    return username;
}

public void setUsername(String username)
{
    this.username = username;
}

public String getJob()
{
    return job;
}

public void setJob(String job)
{
    this.job = job;
}

public String getAge()
{
    return age;
}

public void setAge(String age)
{
    this.age = age;
}}

Make some model using this website. I have done these above code using this website.

Now, do this

@Get<"url">
call<Example> get()



回答3:


if you have to use this json format

{"result":[{"userid":"1","username":"Luis","job":"developer","age":"23"}]}

you have to create two models like this:

class Result {

     @SerializedName("result")
     @Expose
     List<ResultDetail> result; 
} 

class ResultDetail {

     @SerializedName("userid")
     @Expose
     String userId ;// use int instead 
     String username;
     String job;
     String age; // use int instead
}

add GsonConverterFactory to your app build.gradle

com.squareup.retrofit2:converter-gson:2.14

now build retrofit instance :

 Retrofit retrofit = new Retrofit.Builder()
.baseUrl("some base url like : www.example.com/api/")
.addConverterFactory(GsonConverterFactory.create())
.build();

 YourSerivce service = retrofit.create(YourService.class);


 interface YourService {
   @GET("someThing")  // complete url is www.example.com/api/someThing
   Call<Result> getResult();
 }

and finally get result like this :

retrofit.getResult().enqueue(.....)



回答4:


After a lot of testing guided by the 3 answers given and some video tutorial I finally figure it out.

ApiClient:

public class ApiClient {

    private static final String BASE_URL="http://192.168.31.206/";
    public static Retrofit retrofit = null;
    public static ApiInterface instance=null;

    public static Retrofit getApiClient(){

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

    public static ApiInterface getInterface(){

        if (instance==null){
            instance=getApiClient().create(ApiInterface.class);
        }


        return instance;
    }

}

ApiInterface:

public interface ApiInterface {

    //this could be test1_database/getAllUser.json
    @GET("test1_database/getAllUser.php")
    Call<Result> getWorkers();


}

Workers (POJO) class:

public class Workers {


    @SerializedName("userid")
    private String userid;
    @SerializedName("username")
    private String username;
    @SerializedName("job")
    private String job;
    @SerializedName("age")
    private String age;

    public String getUserid() {
        return userid;
    }

    public void setUserid(String userid) {
        this.userid = userid;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getJob() {
        return job;
    }

    public void setJob(String job) {
        this.job = job;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

}

Result (POJO) class:

public class Result {

    @SerializedName("result")
    private List<Workers> result = null;

    public List<Workers> getResult() {
        return result;
    }

    public void setResult(List<Workers> result) {
        this.result = result;
    }

}

MainActivity class:

public class MainActivity extends AppCompatActivity {

    RecyclerView recyclerView;
    List<Workers> list = new ArrayList<>();
    WorkerAdapter adapter;

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

        recyclerView = findViewById(R.id.recycler);
        recyclerView.setHasFixedSize(true);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);

        ApiInterface apiCall = ApiClient.getInterface();
        Call<Result> call = apiCall.getWorkers();

       call.enqueue(new Callback<Result>() {
           @Override
           public void onResponse(Call<Result> call, Response<Result> response) {
               list = response.body().getResult();
               adapter = new WorkerAdapter(MainActivity.this,list);
               recyclerView.setAdapter(adapter);
           }

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

           }
       });

    }}

I am Showing the results in a recyclerview using this adapter:

public class WorkerAdapter extends RecyclerView.Adapter<WorkerAdapter.ViewHolder>{
    Context context;
    List<Workers> list;

    public WorkerAdapter(Context context,List<Workers> list) {
        this.context = context;
        this.list = list;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(context).inflate(R.layout.item_recycler,parent,false);
        ViewHolder holder = new ViewHolder(v);
        return holder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {

        holder.id.setText(String.valueOf(list.get(position).getUserid()));
        holder.name.setText(list.get(position).getUsername());
        holder.job.setText(list.get(position).getJob());
        holder.age.setText(String.valueOf(list.get(position).getAge()));
    }

    @Override
    public int getItemCount() {
        return list.size();
    }


    public class ViewHolder extends RecyclerView.ViewHolder {

        TextView name, job, age,id;

        public ViewHolder(View itemView) {
            super(itemView);
            id = (TextView) itemView.findViewById(R.id.idtxt);
            name= (TextView) itemView.findViewById(R.id.nametxt);
            job=(TextView) itemView.findViewById(R.id.jobtxt);
            age=(TextView) itemView.findViewById(R.id.agetxt);
        }
    }
}

Thanks everyone for your help!



来源:https://stackoverflow.com/questions/52685409/how-to-receive-a-json-array-result-with-retrofit2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!