I am returning a JSON string from PHP:
<?php
$results = array(
"result" => "success",
"username" => "some username",
"projects" => "some other value"
);
echo json_encode($results);
?>
I found a java example online that works. It uses StringBuilder and outputs the response using Toast. I want to actually parse it as a JSON object so I can reference each key=>value, but not sure how to do it. This is the example I am using:
private void tryLogin(String usernameInput, String passwordInput)
{
HttpURLConnection connection;
OutputStreamWriter request = null;
URL url = null;
String response = null;
String parameters = "username=" + usernameInput + "&password=" + passwordInput;
try
{
url = new URL(getString(R.string.loginLocation));
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
request = new OutputStreamWriter(connection.getOutputStream());
request.write(parameters);
request.flush();
request.close();
String line = "";
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
response = sb.toString();
Toast.makeText(this, "Message from server: \n" + response, 0).show();
isr.close();
reader.close();
}
catch(IOException e)
{
Log.i("NetworkTest","Network Error: " + e);
}
}
This is what the code currently returns:
05-04 19:19:54.724: INFO/NetworkTest(1061): {"result":"success","username":"rondog","projects":"1,2"}
Just to be clear, I am pretty sure I know how to parse the string. What I am confused on is getting the response back from the server and pushing that to the JSONObject (or is 'response' the object that I pass?). Any help is appreciated, thanks!
Yes, it is. It expects a string object in it's constructor to parse it.