【问题标题】:Get JSON response in listview and how to show it in listview?在 listview 中获取 JSON 响应以及如何在 listview 中显示它?
【发布时间】:2016-12-02 09:21:32
【问题描述】:

我是 Android 的初学者。我想在列表中获取 JSON 响应并将其显示在 ListView 中。如何做到这一点?
这是我的 JSON 帖子代码。

public class NewTest extends AppCompatActivity {    TextView
txtJson;
       Button btnOkay;
        @Override
       protected void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           setContentView(R.layout.activity_new_test);
            txtJson= (TextView) findViewById(R.id.txtJson);

           assert (findViewById(R.id.btnOkay)) != null;
           (findViewById(R.id.btnOkay)).setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View v) {   new TaskPostWebService("written url here").execute(((TextView)   
findViewById(R.id.txtJson)).getText().toString());

               }
           });  }
       private class TaskPostWebService extends AsyncTask<String,Void,String> {
           private String url;
           private ProgressDialog progressDialog;
           private JSONParser jsonParser;

           public TaskPostWebService(String url ){

               this.url = url;
           }
           @Override
           protected void onPreExecute() {
               super.onPreExecute();
               progressDialog = ProgressDialog.show(NewTest.this,"","");
           }

           @Override
           protected String doInBackground(String... params) {

            String fact = "";
               try {

                   final MediaType JSON = MediaType.parse("application/json");

                   android.util.Log.e("charset", "charset - " + JSON.charset());
                   OkHttpClient client = new OkHttpClient();
       //Create a JSONObject with the data to be sent to the server
                   final JSONObject dataToSend = new JSONObject()
                           .put("nonce", "G9Ivek")
                           .put("iUserId", "477");

                   android.util.Log.e("data - ", "data - " + dataToSend.toString());
       //Create request object
                   Request request = new Request.Builder()
                           .url("written url here")
                           .post(RequestBody.create(JSON, dataToSend.toString().getBytes(Charset.forName("UTF-8"))))
                           .addHeader("Content-Type", "application/json")
                           .build();

                   android.util.Log.e("request - ", "request - " + request.toString());
                   android.util.Log.e("headers - ", "headers - " + request.headers().toString());
                   android.util.Log.e("body - ", "body - " + request.body().toString());
       //Make the request
                   Response response = client.newCall(request).execute();
                   android.util.Log.e("response", " " + response.body().string()); //Convert the response to String
                   String responseData = response.body().string();
       //Construct JSONObject of the response string
                   JSONObject dataReceived = new JSONObject(responseData);
       //See the response from the server
                   Log.i("response data", dataReceived.toString());
               }
               catch (Exception e){
                   e.printStackTrace();
               }
               return fact;
           }

           @Override
           protected void onPostExecute(String s) {
               super.onPostExecute(s);
               TextView text = (TextView) findViewById(R.id.txtJson);
               text.setText(s); 
               progressDialog.dismiss();
           }
       }

那么,我怎样才能在列表中获得响应并将其显示在 ListView 中?

【问题讨论】:

标签: android json listview android-studio


【解决方案1】:
ArrayList<JSONObject> arrayListJson;
ArrayList<String> arrayList;
ArrayAdapter<String> adapter;
ListView listView = (ListView) fragmentView.findViewById(R.id.listView);
adapter = new ArrayAdapter<> (getActivity(), android.R.layout.simple_list_item_1, arrayList);
listView.setAdapter(adapter);

现在在一个单独的线程中:

JSONObject jResponse = new JSONObject(responseStr);
JSONArray jArray= jResponse.getJSONArray("OUTER_KEY");
for (int i = 0; i < jArray.length(); i++) {
    JSONObject jsonObject = jArray.getJSONObject(i);
    arrayList.add(jsonObject.optString("INNER_KEY"));
    arrayListJson.add(jsonObject);
}
adapter.notifyDataSetChanged();

【讨论】:

  • 我的 json 响应是这样的 {"shoppingDealsCount":"4","shoppingDeals":[{"deal_id":"13","title":"t2","category": "Entertainment","description":".....}]}],"code":"1","message":"Deals Package list data found"} 那么如何先解析呢?
  • JSONObject jResponse = new JSONObject(responseStr); String dealsCount = jResponse.optString("shoppingDealsCount");
  • JSONArray deals = jResponse.optJSONArray("shoppingDeals"); 等等
  • 谢谢,但仍然收到 org.json.JSONException: Expected ':' after Response at character 10 of {Response{protocol=http/1.1, code=200, message=OK, url=http:// /.....}}
  • 抱歉回复晚了,但我认为您应该先解析 JSON 响应,然后在代码中尝试。 http://json.parser.online.fr/
【解决方案2】:

欢迎来到stackOverflow, 由于您是初学者,因此在完成解决方案之前,您可以考虑并按照以下步骤操作。

1.网络请求: 对于网络请求,我们有 lib volley (by Google) 和 retrofit (by Square)。您可以将其用于网络请求和响应。

2.JSON 解析: 您可以使用 GSON 库或 JSONObject/jsonArray 来解析 json 数据。我会建议您编写自己的解析代码,以便更好地理解 JSON 解析。

3.ListView数据绑定:到这一步,你应该已经解析出list中的数据了(也可以用其他数据结构来存储数据)。创建 Adapter 并将 listview 与适配器绑定。

我没有为此提供解决方案,您应该自己实施,如有任何疑问,请告诉我。 希望这能奏效。

【讨论】:

    猜你喜欢
    • 2019-04-17
    • 2021-07-20
    • 2016-08-19
    • 1970-01-01
    • 1970-01-01
    • 2020-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多