如何在 Android 应用程序中解析动态 JSON?
How to Parse Dynamic JSON in Android App?
所以今天我得到了一个动态 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>
解决方法:
即使 answer solves the problem, it comes with it's own set of problems. Even if you choose to just take the Web View cookies and scrape the data from it, the app might crash when there is no internet connection. You can follow up this thread here 了解更多信息。
看起来你在 json.php 上的 JSON 是错误的
echo '{"userinfo": [{"status": "loggedout","id": "0": ""}]}';
应该是
echo '{"userinfo": [{"status": "loggedout","id": "0"}]}';
您通过 WebView
将有关登录或未登录的信息存储在 cookie 或会话中,但您希望使用 http 客户端访问该数据。我认为最好在访问 json 之前同步 cookie 和会话。为此,请检查 this and this.
所以今天我得到了一个动态 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>
解决方法:
即使
看起来你在 json.php 上的 JSON 是错误的
echo '{"userinfo": [{"status": "loggedout","id": "0": ""}]}';
应该是
echo '{"userinfo": [{"status": "loggedout","id": "0"}]}';
您通过 WebView
将有关登录或未登录的信息存储在 cookie 或会话中,但您希望使用 http 客户端访问该数据。我认为最好在访问 json 之前同步 cookie 和会话。为此,请检查 this and this.