[Programming] Simple JSON Android Tutorial – hai guys, tutorial kali ini akan membahas tentang penggunaan
json di android.
Seperti anda ketahui JSON merupakan salah satu cara yang biasa
digunakan untuk pertukaran data. Contoh website yang menggunakan
JSON yakni twitter, jika anda sudah biasa menggunakan API twitter maka anda tidak akan asing dengan yang namanya JSON.
Untuk mengolah data melalui JSON saya membiasakan menggunakan kelas
tersendiri, dikarenakan bisa digunakan untuk lain waktu. Contoh kelas
untuk mengolah data dari json seperti berikut :
06 | package id.jay.emrs.service; |
08 | import java.io.BufferedReader; |
09 | import java.io.IOException; |
10 | import java.io.InputStream; |
11 | import java.io.InputStreamReader; |
12 | import java.io.UnsupportedEncodingException; |
13 | import org.apache.http.HttpEntity; |
14 | import org.apache.http.HttpResponse; |
15 | import org.apache.http.client.ClientProtocolException; |
16 | import org.apache.http.client.methods.HttpPost; |
17 | import org.apache.http.impl.client.DefaultHttpClient; |
18 | import org.json.JSONException; |
19 | import org.json.JSONObject; |
21 | import android.util.Log; |
23 | public class JSONparser { |
24 | static InputStream is = null ; |
25 | static JSONObject jObj = null ; |
26 | static String json = "" ; |
32 | public JSONObject getJSONFromUrl(String url) { |
36 | DefaultHttpClient httpClient = new DefaultHttpClient(); |
37 | HttpPost httpPost = new HttpPost(url); |
39 | HttpResponse httpResponse = httpClient.execute(httpPost); |
40 | HttpEntity httpEntity = httpResponse.getEntity(); |
41 | is = httpEntity.getContent(); |
43 | } catch (UnsupportedEncodingException e) { |
46 | } catch (ClientProtocolException e) { |
49 | } catch (IOException e) { |
55 | BufferedReader reader = new BufferedReader( new InputStreamReader( |
56 | is, "iso-8859-1" ), 8 ); |
57 | StringBuilder sb = new StringBuilder(); |
60 | while ((line = reader.readLine()) != null ) { |
61 | sb.append(line + "\n" ); |
67 | } catch (Exception e) { |
69 | Log.e( "BUffer Error" , "Error converting result" + e.toString()); |
74 | jObj = new JSONObject(json); |
75 | } catch (JSONException e) { |
77 | Log.e( "Json parser" , "error parsing data" + e.toString()); |
simpan dengan nama JSONparser.java