I get some data on an URL. There's my server script :
$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.. I get theses datas on my Android App. This is what my App get from the script :
[{"category":"Animals","category_color":"green"},
{"category":"Art","category_color":"orange"},
{"category":"Sport","category_color":"blue"},
{"category":"Video games","category_color":"red"}]
And there's my App code, to get my datas (this is my first App so some code found on Internet helped me) :
@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;
}
I've tried a lot of stuff to parse theses datas into a HashMap ([category, category_color] for each element) like this :
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();
I found this result everytime for each response on Stack. But when I tried this code, my console has printed : E/JSON Task: Cound not parse malformed JSON when I try to do : " JSONObject json = new JSONObject(result);
So, there is my final question :
What is the best way to get an HashMap from a JSON get from my php script ? A simple link can be useful, but at the moment, I can't found a clean working answer.
You need to use
JSONArray json = new JSONArray(result);
since your received data is a JSONArray, not a JSONObject.
Best way to get data from php script is to create array
{
"result": [
{
"category": "Animals",
"category_color": "green"
},
{
"category": "Art",
"category_color": "orange"
}
]
}
you can get data in above format by following script
$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);
prase data by following code
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
}
尝试使用JSON解析工具Gson或Jackson节省您的时间
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.