JSONArray给出了Exception

时间:2014-09-23 09:55:50

标签: php android json

我有这个例外

Value of type java.lang.String cannot be converted to JSONArray

尝试解析JSON时。

JSONParser.java

public class JSONParser {

static InputStream is = null;
static JSONArray jArray = null;
static String json = "";

// constructor
public JSONParser() {

}

// function get json from url
// by making HTTP POST or GET mehtod
public JSONArray makeHttpRequest(String url, String method,
        List<NameValuePair> params) {

    // Making HTTP request
    try {

        // check for request method
        if(method == "POST"){
            // request method is POST
            // defaultHttpClient

            System.out.println("in post, url: "+url);

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        }else if(method == "GET"){

            System.out.println("in get, url: "+url);

            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");

            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity(); 
            is = httpEntity.getContent();

        }            

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"),8);

        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jArray = new JSONArray(json);
        System.out.println("jArray: "+jArray);

    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jArray;

  }
}

NewsActivity.java

public class NewsActivity extends Activity {

    ListView newsListView;

    // Progress Dialog
    private ProgressDialog pDialog;

    // Creating JSON Parser object
    JSONParser jsonParser = new JSONParser();

    ArrayList<HashMap<String, String>> newsList;

    // products JSONArray
    JSONArray News = null;

    NewsAdapter newAdapter;

    ImageButton home;

    // News JSON url
    // http://www.giga-soft.com/fredericm_mobile
    private static final String NEWS_URL = "my_URL.php";

    // ALL JSON node names
    static final String NEWS_ID = "news_id";
    static final String NEWS_CONTENT = "news_content";
    static final String NEWS_PHOTO = "news_photo";
    static final String NEWS_PHOTO_THUMB = "news_photo_thumb";
    static final String NEWS_CREATED_DATE = "news_created_date";
    static final String NEWS_ORD = "news_ord";
    static final String NEWS_STATE = "news_state";
    static final String NEWS_LAST_UPDATE = "news_last-update";
    static final String NEWS_TITLE = "news_title";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.news_list);

        newsListView = (ListView)findViewById(R.id.news_list);
        newsListView.setItemsCanFocus(true);

        // Hashmap for ListView
        newsList = new ArrayList<HashMap<String, String>>();

        home = (ImageButton) findViewById(R.id.TitleHomeBtn);

        home.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                Intent intent = new Intent(NewsActivity.this, MainActivity.class);
                startActivity(intent);

            }
        });

        // Loading News in Background Thread
        new LoadNews().execute();

    }


    /**
     * Background Async Task to Load all News messages by making HTTP Request
     * */
    class LoadNews extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(NewsActivity.this);
            pDialog.setMessage(getResources().getString(R.string.loadNews));
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting News JSON
         * */
        protected String doInBackground(String... args) {

            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();

            // getting JSON string from URL
            JSONArray jsonArray = jsonParser.makeHttpRequest(NEWS_URL, "GET", params);

            ///////////////// the following line gives Exception /////////////////////
            System.out.println("jsonArray.length(): "+jsonArray.length());

            JSONObject jsonObject = null;


            // Check your log cat for JSON reponse
            Log.d("News JSON: ", jsonArray.toString());

            try {

                // looping through All messages
                for (int i = 0; i < jsonArray.length(); i++) {
                    jsonObject = jsonArray.getJSONObject(i);

                    System.out.println("jsonObject: "+jsonObject);

                    // Storing each json item in variable
                    String news_id = jsonObject.getString(NEWS_ID);
                    String news_content = jsonObject.getString(NEWS_CONTENT);
                    String news_photo = jsonObject.getString(NEWS_PHOTO);
                    String news_photo_thumb = jsonObject.getString(NEWS_PHOTO_THUMB);
                    String news_created_date = jsonObject.getString(NEWS_CREATED_DATE);
                    String news_ord = jsonObject.getString(NEWS_ORD);
                    String news_state = jsonObject.getString(NEWS_STATE);
                    String news_last_update = jsonObject.getString(NEWS_LAST_UPDATE);
                    String news_title = jsonObject.getString(NEWS_TITLE);

                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    map.put(NEWS_ID, news_id);
                    map.put(NEWS_CONTENT, news_content);
                    map.put(NEWS_PHOTO, news_photo);
                    map.put(NEWS_PHOTO_THUMB, news_photo_thumb);
                    map.put(NEWS_CREATED_DATE, news_created_date);
                    map.put(NEWS_ORD, news_ord);
                    map.put(NEWS_STATE, news_state);
                    map.put(NEWS_LAST_UPDATE, news_last_update);
                    map.put(NEWS_TITLE, news_title);

                    // adding HashList to ArrayList
                    newsList.add(map);
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    newAdapter = new NewsAdapter(NewsActivity.this, newsList);
                    // updating listview
                    newsListView.setAdapter(newAdapter);

                }
            });

        }

    }

}
php文件中的

<?php
include ('config.php');

mysql_query('SET CHARACTER SET UTF8');
mysql_query("SET NAMES utf8; ");

$check = mysql_query("SELECT * FROM news WHERE 1");

while($row=mysql_fetch_assoc($check))
$output[]=$row;

    $json_encode =json_encode($output);
    $utf8_decode = utf8_decode($json_encode);
    echo $json_encode;
    mb_convert_encoding($json_encode, 'UTF-8');
    $html_entity_decode = html_entity_decode($json_encode);

mysql_close();

php代码:

    ?[
      {
        "news_id": "11",
        "news_content": "\u0639\u0637\u0648\u0631 \u0628\u0623\u062e\u0641 \u0627\u0644\u0627\u062d\u062c\u0627\u0645 \u062a\u0635\u0644\u062d \u0644\u062c\u0645\u064a\u0639 \u0627\u0644\u0627\u0633\u062a\u0639\u0645\u0627\u0644\u0627\u062a \u0627\u0644\u064a\u0648\u0645\u064a\u0629.. \u0648\u062a\u0624\u062e\u0630 \u0627\u0644\u0649 \u0627\u064a \u0645\u0643\u0627\u0646 \u0648\u062a\u0648\u0636\u0639 \u0641\u064a \u0627\u064a \u0645\u0643\u0627\u0646 \u0628\u0633\u0647\u0648\u0644\u0629 .. \u0628\u0627\u0644\u0627\u0636\u0627\u0641\u0629 \u0627\u0644\u0649 \u0639\u0637\u0631\u0647\u0627 \u0627\u0644\u062e\u0644\u0627\u0628",
        "news_photo": "http:\/\/www.abarid.com\/Mobile_apps\/products_thumb\/Untitled6.png",
        "news_photo_thumb": "",
        "news_internal_photo": "http:\/\/www.abarid.com\/Mobile_apps\/products_thumb\/Untitled6.png",
        "news_photo_internal_thumb": "",
        "news_created_date": "2013-10-31",
        "news_ord": "1",
        "news_state": "1",
        "news_last-update": "2013-11-13 23:20:39",
        "news_title": "Pocket Perfums"
      },
      {
        "news_id": "12",
        "news_content": "\u0627\u0644\u0637\u0628\u064a\u0639\u0629 \u062f\u0627\u0626\u0645\u0627 \u0627\u0641\u0636\u0644.. \u0645\u0645\u064a\u0632\u0627\u062a \u0627\u0644\u0645\u0643\u064a\u0627\u062c \u0627\u0644\u0645\u0639\u062f\u0646\u0649\n\u0628\u0648\u062f\u0631\u0629 \u062f\u0642\u064a\u0642\u0629 \u0644\u0627 \u062a\u0633\u062f \u0645\u0633\u0627\u0645 \u0627\u0644\u062c\u0644\u062f \u0648 \u062a\u0633\u0627\u0639\u062f \u0627\u0644\u062c\u0644\u062f \u0639\u0644\u0649 \u0627\u0644\u062a\u0646\u0641\u0633\n\u0645\u062b\u0627\u0644\u064a\u0629 \u0644\u0644\u062c\u0644\u062f \u0627\u0644\u062d\u0633\u0627\u0633 \u0627\u0648 \u0627\u0644\u0645\u062a\u0636\u0631\u0631 - \u0645\u0627\u0646\u0639 \u0637\u0628\u064a\u0639\u0649 \u0636\u062f \u0627\u0634\u0639\u0629 \u0627\u0644\u0634\u0645\u0633 \u0627\u0644\u0636\u0627\u0631\u0629",
        "news_photo": "http:\/\/www.abarid.com\/Mobile_apps\/products_thumb\/Untitled8.png",
        "news_photo_thumb": "",
        "news_internal_photo": "http:\/\/www.abarid.com\/Mobile_apps\/products_thumb\/Untitled8.png",
        "news_photo_internal_thumb": "",
        "news_created_date": "2013-10-31",
        "news_ord": "2",
        "news_state": "1",
        "news_last-update": "2013-11-13 23:20:45",
        "news_title": "\u0627\u0644\u0645\u0643\u064a\u0627\u062c \u0627\u0644\u0645\u0639\u062f\u0646\u064a"
      },
      {
        "news_id": "13",
        "news_content": "\u0644\u0627\u0637\u0644\u0627\u0644\u0629 \u0645\u062a\u0645\u064a\u0632\u0629 \u0648\u0627\u0646\u064a\u0642\u0629 \u062a\u062a\u0645\u064a\u0632 \u0628\u0631\u0642\u0629 \u0627\u0644\u062a\u0635\u0645\u064a\u0645 ",
        "news_photo": "http:\/\/www.abarid.com\/Mobile_apps\/products_thumb\/Untitled9.jpeg",
        "news_photo_thumb": "http:\/\/www.abarid.com\/Mobile_apps\/products_thumb\/Untitled9.jpeg",
        "news_internal_photo": "",
        "news_photo_internal_thumb": "",
        "news_created_date": "2013-12-30",
        "news_ord": "3",
        "news_state": "1",
        "news_last-update": "2014-02-21 01:47:15",
        "news_title": "\u0633\u0648\u0627\u0631 \u0627\u0644\u0631\u062c\u0644 \u0627\u0644\u0645\u062a\u0645\u064a\u0632"
      },
      {
        "news_id": "14",
        "news_content": "\u0639\u0631\u0636 \u0631\u0627\u0626\u0639 \u0645\u0646 \u0641\u0631\u064a\u062f\u0631\u064a\u0643 \u0627\u0645",
        "news_photo": "http:\/\/www.giga-soft.com\/fredericm\/uploads\/152488.png?r=169902398",
        "news_photo_thumb": "http:\/\/www.giga-soft.com\/fredericm\/uploads\/152488_thumb.png?r=169902398",
        "news_internal_photo": "",
        "news_photo_internal_thumb": "",
        "news_created_date": "2013-12-31",
        "news_ord": "4",
        "news_state": "1",
        "news_last-update": "2013-12-31 17:09:10",
        "news_title": "\u0627\u0633\u0648\u0631\u0629 \u0642\u0644\u0628 \u0627\u0644\u064a\u0627\u0642\u0648\u062a"
      }
    ]

导致异常以及如何解决的错误是什么? 希望有人能帮助我。

3 个答案:

答案 0 :(得分:0)

您是否检查了传递给JSONArray的值,是否符合您的预期? 您的问题可能与Value of type java.lang.String cannot be converted to JSONArray

重复

答案 1 :(得分:0)

您应该向HttpPost添加setContent("application/json")以确保它将接收JSON对象。

请参阅documentation

答案 2 :(得分:0)

public class JSONParser {

    static String response = null;
    public final static int GET = 1;
    public final static int POST = 2;

    public ServiceHandler() {

    }

    /**
     * Making service call
     * @url - url to make request
     * @method - http request method
     * */
    public String makeServiceCall(String url, int method) {
        return this.makeServiceCall(url, method, null);
    }

    /**
     * Making service call
     * @url - url to make request
     * @method - http request method
     * @params - http request params
     * */
    public String makeServiceCall(String url, int method,
            List<NameValuePair> params) {
        try {
            // http client
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpEntity httpEntity = null;
            HttpResponse httpResponse = null;

            // Checking http request method type
            if (method == POST) {
                HttpPost httpPost = new HttpPost(url);
                // adding post params
                if (params != null) {
                    httpPost.setEntity(new UrlEncodedFormEntity(params));
                }

                httpResponse = httpClient.execute(httpPost);

            } else if (method == GET) {
                // appending params to url
                if (params != null) {
                    String paramString = URLEncodedUtils
                            .format(params, "utf-8");
                    url += "?" + paramString;
                }
                HttpGet httpGet = new HttpGet(url);

                httpResponse = httpClient.execute(httpGet);

            }
            System.out.println("Status in url =====" + httpResponse.getStatusLine().getStatusCode());
            httpEntity = httpResponse.getEntity();
            response = EntityUtils.toString(httpEntity);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return response;

    }
}