I have Android app connected to MySQL database, everything works fine with the connection, but the data retrieved from database comes in JSON format, I use this class for connection:
public class CommunicatetoServer extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
String response = "";
String url = params[0];
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet(url);
HttpResponse getResponse = httpClient.execute(httpPost);
final int statusCode = getResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w(getClass().getSimpleName(),
"Error " + statusCode + " for URL " + url);
return null;
}
HttpEntity getResponseEntity = getResponse.getEntity();
is = getResponseEntity.getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(is));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
Log.d("IO", e.getMessage().toString());
e.printStackTrace();
}
// return JSON String
return response;
}
protected void onPostExecute(String response)
{
//onPostExecute
Log.d("Server Response : ", response.toString());
Toast.makeText(context, response.toString(), Toast.LENGTH_LONG).show();
}
}
And I apply it like this:
private void GetComments() {
new CommunicatetoServer().execute(SERVER_URL + "GetComments.php");
}
The method above is to retrieve all comments information from the database, and it comes in this way (the data is for test only):
[{"Uname":"test1","Id":"1","DateTime":"2015-03-04 00:00:00","comment":"Hello"},{"Uname":"test3","Id":"1","DateTime":"2015-02-04 10:23:42","comment":"asdffgsdg asdf"}]
So how can I convert it to java object?
Thank you.