Sunday, July 10, 2011

Another example to parse JSON

it's another exercise to parse the following JSON:
{"id":12,"name":12,"status":"ok","volumes":[{"id":17592,"name":"root","status":"ok"}]}

Another example to parse JSON

package com.exercise.AndroidJSON;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

public class AndroidJSONActivity extends Activity {

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

TextView JsonSrc = (TextView)findViewById(R.id.json_src);
TextView JsonResult = (TextView)findViewById(R.id.json_result);
/*
* JSON:
* {"id":12,"name":12,"status":"ok","volumes":[{"id":17592,"name":"root","status":"ok"}]}
*/
final String customJSON = "{\"id\":12,\"name\":12,\"status\":\"ok\",\"volumes\":[{\"id\":17592,\"name\":\"root\",\"status\":\"ok\"}]}";
JsonSrc.setText(customJSON);
try {
JSONObject jsonObject = new JSONObject(customJSON);
String myId = jsonObject.getString("id");
String myName = jsonObject.getString("name");
String myStatus = jsonObject.getString("status");
String stringJsonResult = "id: " + myId + "\n"
+ "name: " + myName + "\n"
+ "status: " + myStatus;


JSONArray jsonArray = jsonObject.getJSONArray("volumes");
JSONObject arrayElement_0 = jsonArray.getJSONObject(0);
String ele0_id = arrayElement_0.getString("id");
String ele0_name = arrayElement_0.getString("name");
String ele0_status = arrayElement_0.getString("status");
stringJsonResult += "\n\nArray Element 0 - \n"
+ "id: " + ele0_id + "\n"
+ "name: " + ele0_name + "\n"
+ "status: " + ele0_status;

JsonResult.setText("\n" + stringJsonResult);

} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(AndroidJSONActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
}
}


Related article:
- Parse JSON with JSONObject
- Get array elements in JSON
- Parse JSON returned from Flickr Services


Remark:
It's a online JSON Viewer, http://jsonviewer.stack.hu/, convert JSON Strings to a Friendly Readable Format. It can be used to validate JSON also.

2 comments:

Peter said...

This is good, but you should use Gson, it's the easiest ;) . Keep up the good work .

Yasir Arafath said...

Nice.. Than q for such post..!