JSON使用Retrofit解析android

时间:2017-10-31 09:52:16

标签: java android json retrofit retrofit2

我希望使用json解析retrofit2,但我的代码不起作用

此网络服务是:(请检查网络服务): http://services.groupkt.com/country/search?text=

这是我的模特课:

public class Country {

    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("alpha2_code")
    @Expose
    private String alpha2Code;
    @SerializedName("alpha3_code")
    @Expose
    private String alpha3Code;

    public String getName() {
        return name;
    }

    public void setName(String name) {
       this.name = name;
    }

    public String getAlpha2Code() {
       return alpha2Code;
    }

    public void setAlpha2Code(String alpha2Code) {
        this.alpha2Code = alpha2Code;
    }

    public String getAlpha3Code() {
        return alpha3Code;
    }

    public void setAlpha3Code(String alpha3Code) {
        this.alpha3Code = alpha3Code;
    }
} 

public class CountryResponse {


    @SerializedName("messages")
    @Expose
    private List<String> messages = null;
    @SerializedName("result")
    @Expose
    private List<Country> countryList = null;


    public List<String> getMessages() {
        return messages;
    }

    public void setMessages(List<String> messages) {
        this.messages = messages;
    }

    public List<Country> getCountryList() {
        return countryList;
    }

    public void setCountryList(List<Country> countryList) {
        this.countryList = countryList;
    }
}

public class Example {


    @SerializedName("RestResponse")
    @Expose
    private CountryResponse restResponse;

    public CountryResponse getRestResponse() {
        return restResponse;
    }

    public void setRestResponse(CountryResponse restResponse) {
       this.restResponse = restResponse;
    }
}

这是我的界面类:

public interface APIInterface {

    @GET("search?text=")
    Call<Example> getCountries();

}

我为返回改造对象编写了2个类:

public class APIClient {

    private static Retrofit retrofit = null;

    public static Retrofit getClient(String baseUrl) {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder().baseUrl(baseUrl)
                    .addConverterFactory(GsonConverterFactory.create()).build();
         }
        return retrofit;
    }
}


public class APIUtils {

    public static final String BASE_URL = 
"http://services.groupkt.com/country/";

    public static APIInterface getSOService() {
        return APIClient.getClient(BASE_URL).create(APIInterface.class);
    }
}

我的适配器:

public class ResponseAdapter extends 
RecyclerView.Adapter<ResponseAdapter.ViewHolder> {

    private List<Example> mItems;
    private Context mContext;
    Example example;
    CountryResponse countyResponse;

    public ResponseAdapter(Context context, Example example) {

        this.example = example;
        mContext = context;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        Context context = parent.getContext();
        LayoutInflater inflater = LayoutInflater.from(context);
        View view = inflater.inflate(R.layout.item_list, parent, false);
        ViewHolder viewHolder = new ViewHolder(view);

        return viewHolder;
    }

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

        Example example = mItems.get(position);
        TextView textView = holder.name;

        textView.setText(example.getRestResponse()
                .getCountryList().get(position).getName());

        TextView textView1 = holder.alpha;

        textView1.setText(example.getRestResponse().
                  getCountryList().get(position).getAl
                                   pha2Code());

        TextView textView2 = holder.alpha2;


          textView2.setText(example.getRestResponse().
                    getCountryList().get(position).getAl
                             pha3Code());

}

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

    public void updateAnswers(CountryResponse countryRes) {
        countyResponse = countryRes;
        notifyDataSetChanged();
    }

    private Example getItem(int adapterPosition) {
        return mItems.get(adapterPosition);
    }


     public interface PostItemListener {
        void onPostClick(long id);
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        TextView name, alpha, alpha2;

        public ViewHolder(View itemView) {
            super(itemView);

            name = (TextView) itemView.findViewById(R.id.name);
            alpha = (TextView) itemView.findViewById(R.id.alpha);
            alpha2 = (TextView) itemView.findViewById(R.id.alpha2);
        }
    }
}

和我的活动:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_response);
        apiInterface= APIUtils.getSOService();
        mRecyclerView= (RecyclerView) findViewById(R.id.my_recycler_view);
        mAdapter=new ResponseAdapter(this,new Example());

        RecyclerView.LayoutManager layoutManager = new 
LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.setHasFixedSize(true);

        loadAnswers();
    }

    private void loadAnswers() {

        apiInterface.getCountries().enqueue(new Callback<Example>() {
            @Override
            public void onResponse(Call<Example> call, Response<Example> 
 response) {
                mAdapter.updateAnswers(response.body().getRestResponse());
            }

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

            }
        });
    }

运行显示

的错误

'java.util.Iterator java.util.List.iterator()' on a null object reference

1 个答案:

答案 0 :(得分:3)

你有

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

public void updateAnswers(CountryResponse countryRes) {
    countyResponse = countryRes;
    notifyDataSetChanged();
}

您的列表首先未初始化。其次,您需要使用项目填充列表。并且您的列表必须是国家列表而不是类型示例

您需要更改为

public void updateAnswers(CountryResponse countryRes) {
    mItems.addAll(countryRes.getCountryList())
    notifyDataSetChanged();
}

并初始化列表

List<Country> mItems = new ArrayList();
// note its of type Country not of Example

最后在onBindViewHolder

中相应地更新您的观点
textView.setText(mItems.get(position).getName());
textView1.setText(mItems.get(position).getAlpha2Code());
textView2.setText(mItems.get(position).getAlpha3Code());