我获得了一些关于URL的数据。这是我的服务器脚本:
$db = null;
$results = "{}";
require_once("connect.php");
/* Query */
if($db != null) {
$stmt = $db->prepare("SELECT category, category_color FROM categories ORDER BY category");
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
/* Close db connection */
$db = null;
echo json_encode($results);
Soooo ..我在我的Android应用程序上获得了这些数据。这是我的应用程序从脚本中获得的:
[{"category":"Animals","category_color":"green"},
{"category":"Art","category_color":"orange"},
{"category":"Sport","category_color":"blue"},
{"category":"Video games","category_color":"red"}]
还有我的应用程序代码,以获取我的数据(这是我的第一个应用程序,因此在Internet上找到的一些代码帮助了我):
@Override
protected String doInBackground(String... urls) {
String url = urls[0];
String parsedString;
HttpURLConnection c = null;
try {
URL u = new URL(url);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Content-type", "application/json");
c.setRequestProperty("Content-length", "0");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.setConnectTimeout(this.timeout);
c.setReadTimeout(this.timeout);
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
//Do stuff to parse my JSON to an HashMap
}
} catch(IOException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} finally {
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
}
}
return null;
}
我已经尝试了很多东西将这些数据解析为HashMap(每个元素的[category,category_color]),如下所示:
StringBuilder sb = new StringBuilder();
String line;
try {
BufferedReader r1 = new BufferedReader(new InputStreamReader(c, "UTF-8"));
while ((line = r1.readLine()) != null) {
sb.append(line).append("\n");
}
} finally {
is.close();
}
return sb.toString();
我每次都会在Stack上的每个响应中找到此结果。但是当我尝试这段代码时,我的控制台打印出: E / JSON任务:当我尝试执行时,Cound不解析格式错误的JSON :“ JSONObject json = new JSONObject(result);
所以,最后一个问题是:
从我的PHP脚本中获取JSON的HashMap的最佳方法是什么?一个简单的链接可能很有用,但目前,我找不到一个干净的工作答案。
答案 0 :(得分:0)
您需要使用
JSONArray json = new JSONArray(result);
因为您收到的数据是JSONArray,而不是JSONObject。
答案 1 :(得分:0)
从php脚本获取数据的最佳方法是创建数组
{
"result": [
{
"category": "Animals",
"category_color": "green"
},
{
"category": "Art",
"category_color": "orange"
}
]
}
您可以按照以下脚本
获取上述格式的数据$return_arr = array();
$fetch = mysql_query("SELECT category, category_color FROM categories ORDER BY category");
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
$row_array['category'] = $row[0];
$row_array['category_color'] = $row[1];
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
按照代码
删除数据JSONObject jsonObject = new JSONObject(response); // here response is what you get from php script which is shown at top
JSONArray message = jsonObject.getJSONArray("result");
for (int i = 0; i < message.length(); i++) {
Model model = new Model();
JSONObject temp = message.getJSONObject(i);
String category = temp.getString("category");
String category_color = temp.getString("category_color");
// create array or harshmap to store all data
}
答案 2 :(得分:0)
尝试使用JSON解析工具Gson或Jackson节省您的时间