从httpresponse android处理json的最佳方法

时间:2012-06-18 10:49:11

标签: java 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<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(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"}]}

2 个答案:

答案 0 :(得分:5)

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

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

例如:

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

Java Class将是:

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字符串中的名称完全匹配。

答案 1 :(得分:1)

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

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

相关问题