Tuesday, January 24, 2012

JSON parsing in Blackberry

HttpConnection conn = null;
InputStream in = null;
String _response = null;
Vector _adBeanVector=null;
int code;
try
{
StringBuffer url=new StringBuffer().append(" Insert Json Url");
conn = (HttpConnection) Connector.open(url.toString(), Connector.READ);
conn.setRequestMethod(HttpConnection.GET);

code = conn.getResponseCode();
if (code == HttpConnection.HTTP_OK) {
in = conn.openInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[in.available()];
int len = 0;
while (-1 != (len = in.read(buffer))) {
out.write(buffer);
}
out.flush();
_response = new String(out.toByteArray());
JSONObject resObject=new JSONObject(_response);
String _key =resObject.getString("Insert Json Key");

_adBeanVector = new Vector();
JSONArray newsArray = resObject.getJSONArray("Insert Json Array Key");
if(newsArray.length() > 0)
{
for (int i=0 ;
i <  news Array.length()
 ; i++)
{
Vector _adElementsVector=new Vector();
JSONObject newsObj = newsArray.getJSONObject(i);
_adElementsVector.addElement(newsObj.getString("Insert Json Array Element Key1"));
_adElementsVector.addElement(newsObj.getString("Insert Json Array Element Key2"));
_adBeanVector.addElement(_adElementsVector);
}
}
if (out != null){
out.close();
}
if (in != null){
in.close();
}
if (conn != null){
conn.close();
}
}

} catch (Exception e)
{
Dialog.alert(e.getMessage());
}

2 comments:

Anonymous said...

how to get array element 2, let say if i want to get urlpath or array element 2 and i created in a new thread

Pralabh jain said...

After parsing JSON data goes to vector, so can be access from it.
E.g vector.elementAt(index)