我从PHP返回一个JSON字符串:
<?php
$results = array(
"result" => "success",
"username" => "some username",
"projects" => "some other value"
);
echo json_encode($results);
?>
我在网上找到了一个有效的 java 示例。它使用 StringBuilder 并使用 Toast 输出响应。我想实际将其解析为 JSON 对象,以便我可以引用每个键=>值,但不确定如何做到这一点。这是我使用的示例:
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);
}
}
这是代码当前返回的内容:
05-04 19:19:54.724: INFO/NetworkTest(1061): {"result":"success","username":"rondog","projects":"1,2"}
需要明确的是,我很确定我知道如何解析字符串。我感到困惑的是从服务器获取响应并将其推送到 JSONObject(或者"响应"是我传递的对象吗?任何帮助不胜感激,谢谢!
(或者"响应"是我传递的对象吗?
是的,它是。它期望构造函数中的字符串对象来解析它。