接收JSON java.lang.string无法转换为jsonarray

时间:2013-07-03 14:20:30

标签: java android json eclipse

即时为网站制作应用。它有一个JSON API。我尝试从中获取结果的网址是: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;
    }
}

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

正如你所看到我试图获取这个数字。任何帮助深表感谢!

1 个答案:

答案 0 :(得分:1)

您收到此错误,因为在行

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

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

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

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

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

P.S。请注意,这假设您的JSONObject object实际上包含您问题中字符串所代表的对象。