简体   繁体   English

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

[英]Getting: Error parsing data when i get response from JSON

im writing an app for a site which uses JSON API. 我正在为使用JSON API的网站编写应用程序。 Im trying to parse the JSON but i get: 我试图解析JSON,但我得到:

Error parsing data org.json.JSONException: Value error of type java.lang.String cannot be converted to JSONArray 解析数据org.json.JSONException时出错:java.lang.String类型的值错误无法转换为JSONArray

This is due its a string, i've tried other methods but i can only get information from the first string, because each string has its own randomly generated "filename/id", you can take a look at the json output: 这是由于它是一个字符串,我尝试了其他方法,但是我只能从第一个字符串中获取信息,因为每个字符串都有其自己随机生成的“ filename / 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"}}

Im trying to get it to show both of the "objects" from the json string. 我试图让它显示json字符串中的两个“对象”。 How can i make a lopp for it to find all the items or simply make it list all the "objects" contained in the "error" identifier? 我该如何查找它的所有项,或者只是使其列出“错误”标识符中包含的所有“对象”?

My Main Activity: 我的主要活动:

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

Any help is much appreciated! 任何帮助深表感谢!

You're trying to get the error field as a JSONArray. 您正在尝试将错误字段作为JSONArray获取。 Its a string. 它是一个字符串。 You can't process a string as an array, it throws that exception. 您不能将字符串作为数组处理,它会抛出该异常。 In fact, I don't see any arrays in there at all. 实际上,我根本看不到任何数组。

I would look into using a JSon library like Gson ( https://code.google.com/p/google-gson/ ). 我会考虑使用像Gson( https://code.google.com/p/google-gson/ )这样的JSon库。 You are able to deserialize collections, which is much easier than doing it yourself. 您可以反序列化集合,这比自己完成要容易得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM