从httpresponse android处理json的最佳方法

我用httpclient来调用用django编写的restapi。 它返回了json输出。 我的httpresponse变量存储它,然后将响应转换为字符串,然后转换为json对象,我认为它虽然很有用但很长。 我是java的新手,任何人都可以告诉我,下面代码的最佳替代逻辑是什么

public void onClick(View v) { // TODO Auto-generated method stub HttpClient httpclient = new DefaultHttpClient(); HttpGet httppost = new HttpGet("http://10.0.2.2:8000/api/ca/entry/? format=json&username=pragya"); try { // Add your data //List nameValuePairs = new ArrayList(2); //nameValuePairs.add(new BasicNameValuePair("username", un.getText().toString())); //nameValuePairs.add(new BasicNameValuePair("username", pw.getText().toString())); //httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append((line + "\n")); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } try { JSONObject jsonObject = new JSONObject(sb.toString()); JSONObject meta = jsonObject.getJSONObject("meta"); String limit = meta.getString("limit"); Toast.makeText(HelloWorldActivity.this, limit, Toast.LENGTH_SHORT).show(); JSONArray array = jsonObject.getJSONArray("objects"); String key = array.getJSONObject(0).getString("api_key"); String uname = array.getJSONObject(0).getString("username"); Toast.makeText(HelloWorldActivity.this, uname + " " + key, Toast.LENGTH_SHORT).show(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } //Toast.makeText(HelloWorldActivity.this, sb.toString(), Toast.LENGTH_SHORT).show(); } catch (ClientProtocolException e) { Toast.makeText(HelloWorldActivity.this, e.toString(), Toast.LENGTH_SHORT).show(); // TODO Auto-generated catch block } catch (IOException e) { // TODO Auto-generated catch block Toast.makeText(HelloWorldActivity.this, e.toString(), Toast.LENGTH_SHORT).show(); } } }); 

json如下

 {"meta": {"limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 1}, "objects": [{"api_key": "c87391754b522d0c83b2c8b5e4c8cfd614559632deee70fdf1b48d470307e40e", "homeAddress": "kathmandu", "resource_uri": "/api/ca/entry/1/", "username": "sumit"}]} 

使用谷歌的Gson库,它非常适合这类任务。

您需要做的就是定义一个新类,该类包含具有json对象中的名称的字段,然后使用Gson将Json字符串直接解析到对象中,反之亦然。

例如:

Json看起来像这样: "limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 1

Java类将是:

 public class MyClass { private int limit; private int next; private int offset; private int previous; private int total_count; public int getLimit() { return limit; } public void setLimit(int limit) { this.limit = limit; } public int getNext() { return next; } public void setNext(int next) { this.next = next; } public int getOffset() { return offset; } public void setOffset(int offset) { this.offset = offset; } public int getPrevious() { return previous; } public void setPrevious(int previous) { this.previous = previous; } public int getTotal_count() { return total_count; } public void setTotal_count(int total_count) { this.total_count = total_count; } } 

并使用Gson代码:

  Gson gson = new Gson(); // Or use new GsonBuilder().create(); MyClass myClass = gson.fromJson(json, MyClass.class); // deserializes json into MyClass 

请注意,类字段的名称必须与json字符串中的名称完全匹配。

始终使用AsyncTask执行冗长的非UI任务。 您描述的所有操作,获取json和解析它们都可以在AsyncTask执行。 编写当前在onClick事件中编写的整个代码,并将其写入AsyncTask doInBackground()

请查看以下内容以获取更多详细信息: http : //developer.android.com/reference/android/os/AsyncTask.html