这是我在 PHP 中的 json_encode 示例:
print(json_encode($row));
导致 {"AverageRating":"4.3"} 这很好。
但是在 Java 中,我似乎无法抓住这个 4.3 的值。这是(对于一个 Android 项目)我编辑了不相关的数据。
public class Rate extends ListActivity {
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb = null;
String Item, Ratings, Review, starAvg;
RatingBar ratingsBar;
ArrayList<NameValuePair> param;
public void onCreate(Bundle savedInstanceState) {
starAvg = "0"; // Sets to 0 in case there are no ratings yet.
new starRatingTask().execute();
ratingsBar = (RatingBar) findViewById(R.id.theRatingBar);
class starRatingTask extends AsyncTask<String, String, Void> {
InputStream is = null;
String result = "";
@Override
protected Void doInBackground(String... params) {
String url_select = "http://www.---.com/---/average_stars.php";
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("item", Item));
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
try {
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// read content
is = httpEntity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
try {
BufferedReader br = new BufferedReader(
new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
return null;
}
protected void onPostExecute(Void v) {
String starAvgTwo = null;
try {
jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
starAvg = json_data.getString("AverageRating");
starAvgTwo = starAvg;
}
} catch (JSONException e1) {
Toast.makeText(getBaseContext(), "No Star Ratings!",
Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
Toast.makeText(getBaseContext(), starAvgTwo,
Toast.LENGTH_LONG).show();
ratingsBar.setRating(Float.valueOf(starAvg));
}
}
第二个吐司产生一个空白(我假设一个“” - 空字符串?)。如果我将 toast 变量改回 starAvg,那么它会显示“0”。
如何检索 4.3 的值。