返回JSON并解析java,android

时间:2011-05-04 19:21:15

标签: php android json parsing

我从PHP返回一个JSON字符串:

<?php
$results = array(
    "result"   => "success",
    "username" => "some username",
    "projects" => "some other value"
);

echo json_encode($results);
?>

我在网上发现了一个有效的java示例。它使用StringBuilder并使用Toast输出响应。我想实际将其解析为JSON对象,以便我可以引用每个key =&gt;值,但不知道如何做到这一点。这是我正在使用的例子:

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(或者是'响应'我传递的对象?)。感谢任何帮助,谢谢!

1 个答案:

答案 0 :(得分:0)

  

(或者是'响应'我传递的对象?)

是的,确实如此。它期望它的构造函数中的字符串对象可以解析它。