Home > Uncategorized > Get JSON data using Java

Get JSON data using Java

Mengambil data JSON menggunakan Java juga mudah. Dengan library json-simple.jar yang dapat di download pada situsnya memudahkan untuk meng-ekstrak data. Berikut adalah contoh:

Data asal:

{"student":[
  {"id":"1401010002","name":"DWI LESTARI"},
  {"id":"1401010003","name":"YOANITA YELIANE"}
]} 

Contoh java code:

 
  inputstream = makeHttpGetRequest("http://123.12.13.14/test.php", null);
  scanner = new Scanner(inputstream).useDelimiter("##"); 
  String line = scanner.next();	
  parsejson(line); 

  JSONParser parser = new JSONParser();
  try {
      Object obj = parser.parse(str);
      JSONObject jsonObject = (JSONObject) obj;
      JSONArray arr = (JSONArray) jsonObject.get("student");
      Iterator iterator = arr.iterator();
		while (iterator.hasNext()) {
		    Object objArrayData = iterator.next();
		    System.out.println(objArrayData);
		    
		    Object obj1 = parser.parse(objArrayData.toString());
		    JSONObject jsonObject1 = (JSONObject) obj1;
		    String strId = (String) jsonObject1.get("id");
		    String strName = (String) jsonObject1.get("name");
		    System.out.println(strId, " ", strName);
		}
  } catch (ParseException ex) {
    Logger.getLogger(Osissync.class.getName()).log(Level.SEVERE, null, ex);
  }

hasilnya ada sebagai berikut:

1401010002  DWI LESTARI
1401010003  YOANITA YELIANE
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: