0

这是我在 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 的值。

4

2 回答 2

1

正如我们在原始问题的评论中所讨论的那样,PHP 以单个 JSONObject 而不是数组的形式发送。在当前状态下需要解析为 JSONObject;但是,如果您开始发送一个值对象数组,那么您将使用 JSONArray 来解析它。

于 2012-06-22T22:15:22.913 回答
1

我认为您的 JSON 不包含数组。所以就这样做:

JSONObject jsonObject = new JSONObject(result); //to convert string to be a JSON object
String averageRating = jsonObject.getString("AverageRating"); //get the value of AverageRating variable

并尝试为averageRating 敬酒。

以及如何从 JSON 对象中获取数组?

如果你有 JSON:

{"employees": [
    { "firstName":"John" , "lastName":"Doe" }, 
    { "firstName":"Anna" , "lastName":"Smith" }, 
    { "firstName":"Peter" , "lastName":"Jones" }]
}

然后使用此代码

JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
    JSONObject jsonObject = jsonArray.getJSONObject(i);
    Log.i(Rate.class.getName(), jsonObject.getString("firstName"));
}

该代码将产生

约翰·安娜·彼得

在您的 LogCat 中

于 2012-06-22T22:11:01.370 回答