How to get List from JSON list using Retrofit 2?

前端 未结 2 1435
再見小時候
再見小時候 2021-01-26 20:21

I am new to Android. I need to get a list of strings from a JSON list. It will be added to a Spinner list. I have the list on server like

[{\"bgrou         


        
相关标签:
2条回答
  • 2021-01-26 20:46

    This is sample code :

     GroupService groupService = createService(GroupService.class);
    
     Call<List<Groups>> groupCall = groupService.getGroups();
    
        groupCall.enqueue(new Callback<List<Groups>>() {
                @Override
                public void onResponse(retrofit.Response<List<Groups>> response, Retrofit retrofit) {
    
    
                }
    
                @Override
                public void onFailure(Throwable t) {
                    t.printStackTrace();
    
                }
            });
    

    Interfaces :

    public interface GroupService {
    
    @GET("<URL>")
    Call<List<Groups>> getGroups();
    }
    

    Also create model name Groups.

    I hope this helps you.

    0 讨论(0)
  • 2021-01-26 21:08

    Make the following model class (parcelable)

    package com.example;
    
    import com.google.gson.annotations.Expose;
    import com.google.gson.annotations.SerializedName;
    
    public class Example implements Parcelable {
    
    @SerializedName("bgroup")
    @Expose
    private String bgroup;
    
    public String getBgroup() {
    return bgroup;
    }
    
    public void setBgroup(String bgroup) {
    this.bgroup = bgroup;
    }
    
    
        protected Example(Parcel in) {
            bgroup = in.readString();
        }
    
        @Override
        public int describeContents() {
            return 0;
        }
    
        @Override
        public void writeToParcel(Parcel dest, int flags) {
            dest.writeString(bgroup);
        }
    
        @SuppressWarnings("unused")
        public static final Parcelable.Creator<Example> CREATOR = new Parcelable.Creator<Example>() {
            @Override
            public Example createFromParcel(Parcel in) {
                return new Example(in);
            }
    
            @Override
            public Example[] newArray(int size) {
                return new Example[size];
            }
        };
    }
    

    Than create interface class like this

    public interface ApiService {
    
    @GET("<URL>")
    Call<List<Example>> getBloodGroups();
    }
    

    And finally call retrofit like following :

    Call<List<Example>> call = new RestClient(this).getApiService()
                    .getBloodGroups();
            call.enqueue(new Callback<List<Example>>() {
                @Override
                public void onResponse(Call<List<Example>> call, Response<List<Example>> response) {
    
                }
    
                @Override
                public void onFailure(Call<List<Example>> call, Throwable throwable) {
    
                }
            });
    
    0 讨论(0)
提交回复
热议问题