如何在 Android 中使用 OkHttp 加载 JSON

How to load JSON with OkHttp in Android

我想开发 android 网站应用程序。我想在我的应用程序中使用 OkHttp 加载 Json
我写了这段代码,但是当启动应用程序并隐藏 progressDialog 时,不显示网站数据(来自 json)。
not 显示任何 FC 错误(在 logcat 中),not 显示任何空异常错误(在 logcat), 只是不在我的应用程序中显示网站数据!
我的 json link : JSON link

适配器代码:

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

    private List<okHTTP_dataProvider> mDataSet;
    private Context mContext;

    public okHTTP_adapter(Context context) {
        mContext = context;
        mDataSet = new ArrayList<>();
    }

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

        View view = LayoutInflater.from(mContext).inflate(R.layout.recycler_raw, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.okHTTP_title.setText(mDataSet.get(position).getTitle());
    }

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

    public void remove(int posistion) {
        mDataSet.remove(posistion);
        notifyItemRemoved(posistion);
    }

    public void add(List<okHTTP_dataProvider> models) {
        mDataSet.addAll(models);
        notifyDataSetChanged();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        public TextView okHTTP_title;

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

            okHTTP_title = (TextView) itemView.findViewById(R.id.recycler_raw_title);
        }
    }
}

AsyncTask class代码:

public class okHTTP_info {
    private Context mContext;

    public void getOkHTTP_info(Context context) {
        mContext = context;
        new getInfo().execute(serverIP.getIP());
    }

    private class getInfo extends AsyncTask<String, Void, String> {

        private String ou_response;
        private List<okHTTP_dataProvider> infoModels;

        @Override
        protected void onPreExecute() {
            CustomProcessDialog.createAndShow(mContext);
            infoModels = new ArrayList<>();
        }

        @Override
        protected String doInBackground(String... params) {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(serverIP.getIP())
                    .build();

            Response response;
            try {
                response = client.newCall(request).execute();
                ou_response = response.body().string().trim();
                response.body().close();
                if (ou_response != null) {
                    JSONArray jsonArray = new JSONArray(ou_response);
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        infoModels.add(new okHTTP_dataProvider(
                                jsonObject.getString("title"),
                                jsonObject.getInt("id")));
                    }
                }
            } catch (IOException | JSONException e) {
                e.printStackTrace();
            }
            return ou_response;
        }

        @Override
        protected void onPostExecute(String s) {
            CustomProcessDialog.dissmis();
        }

Activity 代码:

public class okHTTP_Page extends AppCompatActivity {

    private RecyclerView recycler;
    private okHTTP_adapter adaper;

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

        recycler = (RecyclerView) findViewById(R.id.okHTTP_recycler);
        recycler.setHasFixedSize(true);
        recycler.setLayoutManager(new LinearLayoutManager(this));
        adaper = new okHTTP_adapter(this);
        recycler.setAdapter(adaper);

        okHTTP_info info = new okHTTP_info();
        info.getOkHTTP_info(this);
    }
}

注意:请不要给我负分。我是业余爱好者,我需要你的帮助!谢谢大家 <3

首先你的 json 是一个 Json 对象,类似这样:

{.....,"posts":[{"id":5.....}].....}

所以你应该首先得到 jsonObject 然后他们得到带有 "categories" 标签的 jsonArray,像这样:

JSONObject jsonObject = new JSONObject(ou_response);
JSONArray jsonArray = jsonObject.getJSONObject("posts");

然后继续你自己的代码。

其次,您应该在 onPostExecuted() 中使用 notifyDataSetChanged(); 通知更改,因为无法在其他线程中修改视图,只能在 UIThread 中修改。

您正在以错误的方式解析 JSON。在 if(ou_response != null) 块中试试这个:

try {
    JSONObject response = new JSONObject(ou_response);
    JSONArray postsArray = response.getJSONArray("posts");

    for (int i = 0; i < postsArray.length(); i++) {
        JSONObject postObject = postsArray.getJSONObject(i);
        int id = postObject.getInt("id");
        String title = postObject.getString("title");
        Log.i("Data", "Post id: " + id );
        Log.i("Data", "Post title: " + title );
        //Use the title and id as per your requirement
    }
} 
catch (JSONException e) {
      e.printStackTrace();
}