获取:当我从JSON获得响应时解析数据时出错

时间:2013-07-04 20:40:10

标签: android json eclipse string parsing

我正在为使用JSON API的网站编写应用程序。我试图解析JSON,但我得到:

  

解析数据时出错org.json.JSONException:类型的值错误   java.lang.String无法转换为JSONArray

这是因为它是一个字符串,我尝试过其他方法,但我只能从第一个字符串中获取信息,因为每个字符串都有自己随机生成的“文件名/ id”,你可以看看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"}}

我试图让它显示json字符串中的两个“对象”。我怎样才能让它找到所有项目或只是让它列出“错误”标识符中包含的所有“对象”?

我的主要活动:

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");
        TextView txt = (TextView)findViewById(R.id.nodata);

        /**String s = "{menu:{\"1\":\"sql\", \"2\":\"android\", \"3\":\"mvc\"}}";
        JSONObject jObject = null;
        try {
            jObject = new JSONObject(s);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        JSONObject menu = null;
        try {
            menu = jObject.getJSONObject("menu");
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Map<String,String> map = new HashMap<String,String>();
        Iterator<String> iter = menu.keys();
        while(iter.hasNext()){
            String key = (String)iter.next();
            String value = null;

            try {
                value = menu.getString(key);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            map.put(key,value);
            txt.setText(value);
        } **/

        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>>();
        String files = null;
        try {

            int id;
            String name;
            JSONArray array = new JSONArray("error");
            for (int i = 0; i < array.length(); i++) {
                JSONObject row = array.getJSONObject(i);
                id = row.getInt("id");
                name = row.getString("name");
            }

            //JSONArray shows = object.getJSONArray("");
            /*String shows = object.getString("S*");

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

                files = shows;
                //map.put("video_location", "" + e.getString("video_location"));
                //TextView txt = (TextView)findViewById(R.id.nodata);
                //txt.setText(files);
                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[] { files, "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();
        }
    } 
}

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:1)

您正在尝试将错误字段作为JSONArray。它是一个字符串。您不能将字符串作为数组处理,它会抛出该异常。事实上,我根本没有看到任何阵列。

答案 1 :(得分:0)

我会考虑使用像Gson(https://code.google.com/p/google-gson/)这样的JSon库。您可以对集合进行反序列化,这比自己动手更容易。