【问题标题】:return JSON and parse in java, android返回 JSON 并在 java、android 中解析
【发布时间】:2011-08-18 19:50:53
【问题描述】:

我从 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(或者是“响应”我传递的对象?)。任何帮助表示赞赏,谢谢!

【问题讨论】:

  • 我不确定您的问题是什么。
  • 我想我对传递给 JSONObject 的内容感到困惑。我只是通过“响应”吗?几天前我刚开始使用java,所以对我来说很赤裸裸:)
  • 如果 05-04 19:19:54.724: INFO/NetworkTest(1061): {"result":"success","username":"rondog","projects":"1,2"} 是您返回的内容,那么解析器将无法工作,因为字符串中有 `05-04 19:19:54.724:...。你只有什么json字符串没有别的
  • 如果我这样做:JSONObject obj = new JSONObject(response);我收到“JSONObject 无法解析为变量”错误
  • @Ibrahim Diallo 来自 LogCat。它实际上只是括号里的东西

标签: php android json parsing


【解决方案1】:

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

是的,是的。它期望它的构造函数中有一个字符串对象来解析它。

【讨论】:

    猜你喜欢
    • 2014-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多