Parsing JSON using JAVA with HTTP Basic Authentication in JAVA

Hello All,

Today we will explore how to parse JSON String into JSONArray and from JSONArray to List of HashMaps above all to do it with Basic HTTP Authentication, I needed such scenario as I was developing an application for android and I read the data which to be synced from json web service and write it to Sqlite, and because I read so many types I needed a generic json parser above all the json web services is being protected through basic http authentication, so here is what I did.

so lets Start

1. We need to do HTTP Request to get the JSON Stream then we convert the Stream to string out of the target web service, and then parse it to JSONArray.

HttpGet httpget = new HttpGet("url");

JSONArray jsonObjects = ConstructJsonArray(httpget);

private static  JSONArray ConstructJsonArray(HttpGet getQuery) {

	if(user!=null) {

		// im getting the username and password from database as a hashmap this is why im using user.get("") 
		//if you prefer you could add username and password as parameters to this function
		getQuery.addHeader(BasicScheme.authenticate(new UsernamePasswordCredentials(user.get("username"),user.get("password")),"UTF-8",false));
	}

	 HttpResponse response;

	 HttpParams httpParameters = new BasicHttpParams();

	 HttpClient httpclient ;

	 try {
		 httpclient = new DefaultHttpClient(httpParameters);

		 int timeoutConnection = 3000;
		 HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);

		 // Set the default socket timeout (SO_TIMEOUT) in milliseconds
		 int timeoutSocket = 5000;
		 HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

		 response = httpclient.execute(getQuery);

		 HttpEntity entity = response.getEntity();

		  if (entity != null && response.getStatusLine().getStatusCode() == 200) {

			   InputStream instream = entity.getContent();

			   String result = convertStreamToString(instream);

			   instream.close();

			   return new JSONArray(result);
		  }
	 }
	 catch (ClientProtocolException e) 
	 {
	 } 
	 catch (ConnectTimeoutException e)
	 {
	 }
	 catch (IOException e) 
	 {
	 }
	 catch (JSONException e) 
	 {
	 }

	return null;
}

private static String convertStreamToString(InputStream is) {

	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) 
	{
		Log.e(TAG + "ERROR",e.toString());
	}
	finally
	{
		try 
		{
			is.close();
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
			//Log.e(TAG + "ERRO",e.toString());
		}
	}

	return sb.toString();
}

2. Now we need to Parse JSONArray to List of Hashmaps so we could deal with it in more convenient  ways “toList()“, in order to do so we need away to check if the json entity should be as list item or a map item. and from there add to list as list item or add as hash item inside the list.

public static boolean isEmptyObject(JSONObject obj) {
	return obj.names() == null;
}

public static Map<String, Object> getMap(JSONObject obj, String key) throws JSONException {
	return toMap(obj.getJSONObject(key));
}

public static Map<String, Object> toMap(JSONObject obj) throws JSONException {
	Map<String, Object> map = new HashMap<String, Object>();

	Iterator<String> keys = obj.keys();

	while (keys.hasNext()) {
		String key = (String) keys.next();
		map.put(key, convertFromJson(obj.get(key).toString()));
	}

	return map;
}

public static List<HashMap<String, String>> toList(JSONArray array) throws JSONException 
{
	List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();

	if( array == null || array.length() == 0 )
		return null;

	for (int i = 0; i < array.length(); i++) {
		list.add((HashMap<String, String>) convertFromJson(array.get(i)));
	}

	return list;
}

private static Object convertFromJson(Object json) throws JSONException {

	if (json == JSONObject.NULL) {
		return null;
	} 
	else if (json instanceof JSONObject) {

		return toMap((JSONObject) json);
	}
	else if (json instanceof JSONArray) {

		return toList((JSONArray) json);
	} 
	else {

		return json;
	}
}

I hope that it could help somebody out

Posted in Network, Programming, Technology and tagged , , , , , , , , . Bookmark the permalink. RSS feed for this post. Leave a trackback.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

Swedish Greys - a WordPress theme from Nordic Themepark.