1
我有從json對象獲取值的問題.json_encode返回null到android的字符串。在android應用程序中獲取jsonObject的空值
的logcat:
05-01 22:36:21.653: D/Create Response(801): {}
05-01 22:36:21.653: W/System.err(801): org.json.JSONException: No value
for success
05-01 22:36:21.663: W/System.err(801): at
org.json.JSONObject.get(JSONObject.java:354)
05-01 22:36:21.663: W/System.err(801): at
org.json.JSONObject.getInt(JSONObject.java:443)
MyPhp.php
<?php
header('Content-type=application/json; charset=utf-8');
$response = array();
// check for required fields
if (isset($_POST['B_Name']) && isset($_POST['Au_Name']) &&
isset($_POST['Pub']) && isset($_POST['Pr']) &&
isset($_POST['B_Genre'])) {
$B_Name = $_POST['B_Name'];
$Au_Name = $_POST['Au_Name'];
$Pub = $_POST['Pub'];
$Pr = $_POST['Pr'];
$B_Genre = $_POST['B_Genre'];
// include db connect class
require_once(__DIR__ . '/android/db_connect.php');
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO products(Book_Name, Author_Name, Book_Genre, Price, Publication) VALUES('$B_Name', '$Au_Name', '$B_Genre', '$Pr', '$Pub')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Product successfully created.";
$encoded_rows = array_map('utf8_encode', $response);
echo json_encode($encoded_rows);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
$encoded_rows = array_map('utf8_encode', $response);
echo json_encode($encoded_rows);
}
} else {
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
$encoded_rows = array_map('utf8_encode', $response);
echo json_encode($encoded_rows);
}
這裏是我的一片doInBackground的:
String B_Name = BookName.getText().toString();
String Au_Name = AuthorName.getText().toString();
String Pub = Publication.getText().toString();
String Pr = Price.getText().toString();
String B_Genre = BookGenre.getText().toString();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("B_Name", B_Name));
params.add(new BasicNameValuePair("Au_Name", Au_Name));
params.add(new BasicNameValuePair("Pub", Pub));
params.add(new BasicNameValuePair("Pr", Pr));
params.add(new BasicNameValuePair("B_Genre", B_Genre));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Intent i = new Intent(getApplicationContext(),
MainActivity.class);
startActivity(i);
finish();
}
} catch (JSONException e) {
e.printStackTrace();
}
看起來像你的json字符串是空的:「{}」 – Buddy
好友 - 我知道,但爲什麼? – hdiz