0

我正在为网站制作应用程序。它有一个 JSON API。我试图从中获取结果的 URL 是:http://api.bayfiles.net/v1/account/login/<user>/<password>

我收到错误消息:使用 logcat 记录错误时,java.lang.string 无法转换为 jsonarray。

我的主要活动是:

public class MainActivity extends SherlockActivity {

    EditText un,pw;
    TextView error;
    Button ok;
    private ProgressDialog mDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        un = (EditText)findViewById(R.id.user);
        pw = (EditText)findViewById(R.id.psw);
        ok = (Button)findViewById(R.id.button1);
        error = (TextView)findViewById(R.id.textView1);

        ok.setOnClickListener(new View.OnClickListener() {

             @Override
             public void onClick(View v) {
                 // TODO Auto-generated method stub
                 //error.setText("Clicked");
                 //Intent startNewActivityOpen = new Intent(LoginActivity.this, FilesActivity.class);
                 //startActivityForResult(startNewActivityOpen, 0);

                 JsonAsync asyncTask = new JsonAsync();
                // Using an anonymous interface to listen for objects when task
                // completes.
                asyncTask.setJsonListener(new JsonListener() {
                    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/login/spxc/mess2005");



             }
        });     
    }

    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_id", String.valueOf(i));
                map.put("session", "" + e.getString("session"));
                mylist.add(map);
            }
        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data: " + e.toString());
        }

        error.setText("session");

                /*
                //Intent myIntent = new Intent(ListMoviesController.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();
        }
    }

}

这是我的适配器:JSONfunctions.java

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;
    }
}

为什么我收到这个错误?在 url 中使用正确的用户名和密码时,您将获得:{"error":"","session":"RANDOM NUMBER"}

如您所见,我尝试获取此号码。任何帮助深表感谢!

4

1 回答 1

1

您收到此错误是因为在行

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

您正在尝试获取 key 的值error并将其视为一个数组,而它不是 - 它是一个空字符串。因此,您需要将其作为字符串获取:

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

同样,如果您需要获取“会话”,可以使用

String session = object.getString("session");

PS请注意,这是假设您JSONObject object实际上包含问题中字符串表示的对象。

于 2013-07-03T14:27:22.877 回答