【问题标题】:How to Parse Dynamic JSON in Android App?如何在 Android 应用程序中解析动态 JSON?
【发布时间】:2019-08-07 09:59:14
【问题描述】:

所以今天我得到了一个动态 JSON 文件 "json.php",它会根据用户是否登录来更改其内容。我想在我的 android 应用程序中解析这个 JSON 文件。

我的问题: 我无法在我的 JSON 文件中解析“id”的动态值。 当前问题: 用户是否登录并不重要,json.php 的输出始终是注销状态。我想在我当前的 JSON 解析方法中添加会话支持,就像我的 Web 视图一样。

看看json.php

json.php

<?php
session_start();
if (isset($_SESSION['access_token'])) {
    echo '{"userinfo": [{"status": "loggedin","id": "1"}]}';
} else {
    echo '{"userinfo": [{"status": "loggedout","id": "0"}]}';
}
?>

所以,如果用户登录,json.php 的输出将是这样的,反之亦然:

{"userinfo": [{"status": "loggedin","id": "1"}]}

来到 Android 部分:

MainActivity.java

package com.example.app;
import ...

public class MainActivity extends AppCompatActivity {
private WebView MywebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Firing up the fetchData.java process
        fetchData process = new fetchData();
        process.execute();

        MywebView = (WebView) findViewById(R.id.main); //Assigning WebView to WebView Frame "main".
        MywebView.loadUrl("https://example.com/"); //the url that app is going to open
        MywebView.setWebViewClient(new WebViewClient());

        //set and tweak webview settings from here
        WebSettings MywebSettings = MywebView.getSettings();
        MywebSettings.setJavaScriptEnabled(true);
        MywebSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
    }
}

fetchData.java

我们将此处的 JSON 解析为该文件中的后台进程。我们将“id”转换为字符串,以便我们可以进一步使用它。我得到了这个tutorial的帮助。

package com.example.app;
import ...

public class fetchData extends AsyncTask<Void, Void, Void> {
    @Override
     protected Void doInBackground(Void... voids) {
         HttpHandler sh = new HttpHandler();
         String url = "https://example.com/json.php";
         String jsonStr = sh.makeServiceCall(url);
         String webUserID;
         if (jsonStr != null) {
             try {
                 JSONObject jsonObj = new JSONObject(jsonStr);
                 JSONArray info = jsonObj.getJSONArray("userinfo");
                     JSONObject c = info.getJSONObject(0);
                     webUserID = c.getString("id");
             } catch (final JSONException e) {
                 Log.e("TAG", "Json parsing error: " + e.getMessage());
             }
         } else {
             Log.e("TAG", "Couldn't get JSON from server.");
         }
         //here I do whatever I want with the string webUserID
         //Generally used to set OneSignal External ID
         return null;
     }
}

HttpHandler.java

此外,我们还有一个处理所有请求的 HTTP 处理程序文件。

package com.example.app;
import ...

class HttpHandler {

    private static final String TAG = HttpHandler.class.getSimpleName();

    HttpHandler() {
    }

    String makeServiceCall(String reqUrl) {
        String response = null;
        try {
            URL url = new URL(reqUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());
            response = convertStreamToString(in);
        } catch (MalformedURLException e) {
            Log.e(TAG, "MalformedURLException: " + e.getMessage());
        } catch (ProtocolException e) {
            Log.e(TAG, "ProtocolException: " + e.getMessage());
        } catch (IOException e) {
            Log.e(TAG, "IOException: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
        return response;
    }

    private String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line).append('\n');
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return sb.toString();
    }
}

那么,获得我想要的东西的可能方法是什么?非常感激你的帮助。谢谢。


另外,我添加了 index.php 和 home.php 以防万一。

index.php

<?php
session_start();
if (isset($_SESSION['access_token'])) {
    header('Location: home.php');
    exit();
} elseif (!isset($_SESSION['access_token']) && isset($_COOKIE['access_token'])) {
    $_SESSION['access_token'] = $_COOKIE['access_token'];
    header('Location: home.php');
    exit();
}
if (isset($_POST['login'])) {
    setcookie("access_token", "123456", time()+60*60*24*30);
    $_SESSION['access_token'] = "123456";
    header("Location: home.php");
    exit;
}
?>
<html>
    <head>
        <title>Internal Testing Site</title>
    </head>
    <body>
        <h1>Internal cache testing website</h1>
        <hr>
        <p>You are currently logged out.</p>
        <form method="POST">
            <button name="login">Click me to login</button>
        </form>
    </body>
</html>

home.php

<?php
session_start();
if (!isset($_SESSION['access_token'])) {
    header('Location: index.php');
    exit();
}
?>
<html>
    <head>
        <title>Internal Testing Site</title>
    </head>
    <body>
        <h1>internal cache testing website</h1>
        <hr>
        <p><b>You are currently logged in.</b></p>
        <a href="json.php">See JSON</a>
    </body>
</html>

解决方案: 即使this answer 解决了问题,它也带来了自己的一系列问题。即使您选择只获取 Web View cookie 并从中抓取数据,应用程序也可能在没有互联网连接时崩溃。您可以关注this thread here了解更多信息。

【问题讨论】:

  • 嗨,实际上对我来说一切都很好,但我似乎无法理解确切的问题。你能解释一下到底出了什么问题或者你想达到什么目标?
  • 您确定您的服务器在两种情况下返回正确的 json 吗?
  • @HardikChauhan 好吧,你可以看到 json.php 在用户登录时输出不同的“id”和“state”。所以,当我启动我的应用程序时,登录到网站“示例.com/index.php”并到达“example.com/home.php”,这里的“example.com/json.php”也发生了变化。但是,在 JSON 解析器中,输出保持不变,就好像我从未登录过一样。
  • isset($_SESSION['access_token'],你正确设置了access_token吗?也许如果你不返回每个请求的注销状态。
  • @faranjit 从技术上讲,当我打开我的应用程序时,登录然后从应用程序 webview 本身转到 json.php,我得到了我想要的输出。 JSON 文件显示我已登录。但是,在 JSON 解析器中,JSON 仍处于注销状态。我使用 PHP $_SESSION cookie。 JSON解析器不存储或访问从我相信的webview保存的会话cookie。理想情况下,JSON 解析器应该在下一次应用启动时读取登录状态,就像 WebView 打开 index.php 并找到 cookie 并自动重定向到 home.php

标签: php android json webview android-webview


【解决方案1】:

您通过WebView 将有关登录或未登录的信息存储在cookie 或会话中,但您希望通过http 客户端访问该数据。我认为最好在访问 json 之前同步 cookie 和会话。为此,请检查 thisthis

【讨论】:

  • 好的,所以我应该将 Web 视图的会话和 cookie 与 http 客户端的会话和 cookie 同步。知道了。让我试试这种方法,并尽快回复您!非常感谢您的指导。
  • 嘿,我正在关注this 线程,似乎我解决了我的“需求”,现在可以成功获取用户 ID。但是,当我们使用这种方法时,会出现一个新问题。如果没有互联网连接,应用程序会崩溃。你有解决方法吗?谢谢!由于这是一个不同的问题,我创建了一个 different thread here
【解决方案2】:

看起来你在 json.php 上的 JSON 是错误的

echo '{"userinfo": [{"status": "loggedout","id": "0": ""}]}';

应该是

echo '{"userinfo": [{"status": "loggedout","id": "0"}]}';

【讨论】:

  • 这只是我在这里描述我的问题时犯的一个错字。服务器中的 JSON 代码是正确的!感谢您指出这一点。修复! :)
  • 我希望你能得到我想要达到的总体目标。
  • 现在我知道了,起初感觉像是解析问题,抱歉。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-20
  • 2013-02-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多