0

我正在尝试使用他们的 API 从站点 BayFiles.net 获取一些信息。调用 URL 为:http ://api.bayfiles.net/v1/account/files?session=SESSION-ID

我得到的错误是:

07-04 13:54:39.525: E/log_tag(588): Error parsing data org.json.JSONException: Value  at error of type java.lang.String cannot be converted to JSONArray

正确 sessionID 时的 JSON 输出如下所示:

{
    "error": "",
    "S8tf": {
        "infoToken": "wCfhXe",
        "deleteToken": "gzHTfGcF",
        "size": 122484,
        "sha1": "8c4e2bbc0794d2bd4f901a36627e555c068a94e6",
        "filename": "Screen_Shot_2013-07-02_at_3.52.23_PM.png"
    },
    "S29N": {
        "infoToken": "joRm6p",
        "deleteToken": "IL5STLhq",
        "size": 129332,
        "sha1": "b4a03897121d0320b82059c36f7a10a8ef4c113d",
        "filename": "Stockholmsyndromet.docx"
    }
}

但是我无法捕捉到响应并将其显示在列表视图中。这是我的活动:

    public class FilesActivity extends SherlockListActivity implements
    OnClickListener {

        private ProgressDialog mDialog;
        ActionBar ABS;
        TextView session;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.dblist);

            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle("Files");

            JsonAsync asyncTask = new JsonAsync();
            // Using an anonymous interface to listen for objects when task
            // completes.
            asyncTask.setJsonListener(new JsonListener() {
                @Override
                public void onObjectReturn(JSONObject object) {
                    handleJsonObject(object);
                }
            });
            // Show progress loader while accessing network, and start async task.
            mDialog = ProgressDialog.show(this, getSupportActionBar().getTitle(),
                    getString(R.string.loading), true);
            asyncTask.execute("http://api.bayfiles.net/v1/account/files?session=" + PreferenceManager.getDefaultSharedPreferences(getBaseContext()).getString("sessionID", "defaultStringIfNothingFound"));


            //session = (TextView)findViewById(R.id.textView1);
            //session.setText(PreferenceManager.getDefaultSharedPreferences(getBaseContext()).getString("sessionID", "defaultStringIfNothingFound"));

        }
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

        }   

        private void handleJsonObject(JSONObject object) {
            ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();

            try {

                JSONArray shows = object.getJSONArray("error");

                for (int i = 0; i < shows.length(); i++) {
                    HashMap<String, String> map = new HashMap<String, String>();
                    JSONObject e = shows.getJSONObject(i);


                    //map.put("video_location", "" + e.getString("video_location"));
                    mylist.add(map);
                }
            } catch (JSONException e) {
                Log.e("log_tag", "Error parsing data " + e.toString());
            }

            ListAdapter adapter = new SimpleAdapter(this, mylist, R.layout.dbitems,
                    new String[] { "video_title", "video_location" }, new int[] { R.id.item_title,
                            R.id.item_subtitle });

            setListAdapter(adapter);

            final ListView lv = getListView();
            lv.setTextFilterEnabled(true);
            lv.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {
                    @SuppressWarnings("unchecked")
                    HashMap<String, String> o = (HashMap<String, String>) lv
                            .getItemAtPosition(position);

                    //Intent myIntent = new Intent(ListShowsController.this,
                        //  TestVideoController.class);
                    //myIntent.putExtra("video_title", o.get("video_title"));
                    //myIntent.putExtra("video_channel", o.get("video_channel"));
                    //myIntent.putExtra("video_location", o.get("video_location"));
                    //startActivity(myIntent);
                }
            });

            if (mDialog != null && mDialog.isShowing()) {
                mDialog.dismiss();
            }
        }
    }

and my JSONfunctions:
public class JSONfunctions {

    public static JSONObject getJSONfromURL(String url){
        InputStream is = null;
        String result = "";
        JSONObject jArray = null;

        //http post
        try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);

            try {
                // Add your data
                /*List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                nameValuePairs.add(new BasicNameValuePair("key", "stianxxs"));
                nameValuePairs.add(new BasicNameValuePair("secret", "mhfgpammv9f94ddayh8GSweji"));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); */

                // Execute HTTP Post Request
                HttpResponse response = httpclient.execute(httppost);
                //HttpResponse response = httpclient.execute(httppost);
                HttpEntity httpEntity = response.getEntity();
                is = httpEntity.getContent();

            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
            } catch (IOException e) {
                // TODO Auto-generated catch block
            }

        }catch(Exception e){
                Log.e("log_tag", "Error in http connection "+e.toString());
        }

      //convert response to string
        try{
                BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                }
                is.close();
                result=sb.toString();
        }catch(Exception e){
                Log.e("log_tag", "Error converting result "+e.toString());
        }

        try{

            jArray = new JSONObject(result);            
        }catch(JSONException e){
                Log.e("log_tag", "Error parsing data "+e.toString());
        }

        return jArray;
    }
}

任何帮助深表感谢!

4

1 回答 1

1

由于“错误”不是 JSONArray,它会给您解析错误。

JSONArray shows = object.getJSONArray("error");

将您的线路更改为

String shows = object.getString("error");

您可以参考这些链接进行 JSON 解析。 https://stackoverflow.com/a/16938507/1441666

于 2013-07-04T12:14:35.423 回答