Best way to handle json from httpresponse android

I used httpclient to call restapi written in django. He returned json output. My httpresponse variable saved it, and later converts the response to a string and then to a json object, I think it is lengthy, although it works. I'm really new to java, can someone advise me what is the best alternative logic for the code below

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 looks like this

 {"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"}]} 
0
java json android
Jun 18 2018-12-18T00:
source share
2 answers

Use the Gson library from Google, it is ideal for such tasks.

All you have to do is define a new class containing the fields with the key names in the json object, and then use Gson to parse the Json string directly in the object or vice versa.

So for example:

Json looks like this: "limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 1 .

The Java class will be:

 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; } } 

And use this Gson code:

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

Note that the class field name must exactly match the key name in the json string.

+5
Jun 18 '12 at 12:38
source

Always perform a long task other than a UI using AsyncTask . All operations described by you, the choice of json and their analysis can be performed in AsyncTask . Write all the code that you currently wrote in the onClick event and write it doInBackground() in AsyncTask .

For more information check out the following: http://developer.android.com/reference/android/os/AsyncTask.html

+1
Jun 18 2018-12-18T00:
source



All Articles