尝试获取数据时,JSONArray无法转换为JSONObject错误

时间:2015-05-05 14:26:55

标签: android json

我有一个Android应用程序,通过它我想读json以下的json。

[{"name":"ABCD","country":"INDIA","twitter":"abc"},{"name":"nehasharma","country":"india","twitter":"indore"},{"name":"Arif","country":"India","twitter":"@sdf"},{"name":"gsutam","country":"india","twitter":"hwello"},{"name":"gsutam","country":"india","twitter":"hwello"},{"name":"gsutam","country":"india","twitter":"hwello"},{"name":"gsutam","country":"india","twitter":"hwello"},{"name":"gsutam","country":"india","twitter":"hwello"},{"name":"bawender","country":"18","twitter":null},{"name":"dddd","country":"india","twitter":"sdtt"},{"name":"dddd","country":"india","twitter":"sdtt"},{"name":"dddd","country":"india","twitter":"fghjj"},{"name":"je","country":"xe","twitter":"@rtttt.com\n"},{"name":"ajh","country":"eyohio","twitter":"mp"},{"name":"hasan","country":"jsjs","twitter":"snsns"},{"name":"13.3738383383","country":"38.3838383829","twitter":"location"},{"name":"Latitude:13.07136399","country":"Longitude:77.55943079","twitter":"Current Location"},{"name":"Latitude:13.07136399","country":"Longitude:77.55943079","twitter":"Current Location"},{"name":"Latitude:13.07136399","country":"Longitude:77.55943079","twitter":"Current Location"},{"name":"13.07136399","country":"77.55943079","twitter":"Current Location"},{"name":"13.07136399","country":"77.55943079","twitter":"Current Location"}]

这是android代码。

public class Cultural extends ListActivity {

    private ProgressDialog pDialog;


    private static String url = "http://hmkcode.appspot.com/jsonservlet";

    private static final String NAME = "name";
    private static final String COUNTRY = "country";
    private static final String TWITTER = "twitter";

    // contacts JSONArray
    JSONArray contacts = null;

    // Hashmap for ListView
    ArrayList<HashMap<String, String>> contactList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.cultural);

        contactList = new ArrayList<HashMap<String, String>>();

        ListView lv = getListView();

        // Listview on item click listener
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                        int position, long id) {
                // getting values from selected ListItem

                String name = ((TextView)view.findViewById(R.id.name)).getText().toString();

                String country = ((TextView) view.findViewById(R.id.time)).getText().toString();
                String twitter = ((TextView) view.findViewById(R.id.venue)).getText().toString();

                Intent in = new Intent(getApplicationContext(),SingleEventActivity.class);
                in.putExtra(NAME, name);
                in.putExtra(COUNTRY, country);
                in.putExtra(TWITTER, twitter);

                startActivity(in);

            }
        });

        // Calling async task to get json
        new GetContacts().execute();
    }

    /**
     * Async task class to get json by making HTTP call
     * */
    private class GetContacts extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(Cultural.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            // Creating service handler class instance
            ServiceHandler sh = new ServiceHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

            Log.d("Response: ", "> " + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    // contacts = jsonObj.getJSONArray(NAME);

                    // looping through All Contacts
                    for (int i = 0; i < contacts.length(); i++) {
                        JSONObject c = contacts.getJSONObject(i);

                        String name = c.getString(NAME);
                        String time = c.getString(COUNTRY);
                        String twitter=c.getString(TWITTER);

                        // Phone node is JSON Object

                        // tmp hashmap for single contact
                        HashMap<String, String> contact = new HashMap<String, String>();

                        // adding each child node to HashMap key => value

                        contact.put(NAME, name);
                        contact.put(COUNTRY, time);
                        contact.put(TWITTER,twitter);

                        //contact.put(TAG_ADDRESS, address);

                        // adding contact to contact list
                        contactList.add(contact);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             * */
            ListAdapter adapter = new SimpleAdapter(Cultural.this, contactList,R.layout.list_item, new String[] { NAME, COUNTRY,TWITTER }, new int[] { R.id.name,R.id.time, R.id.venue});

            setListAdapter(adapter);
        }

    }

}

每当我尝试运行应用程序时,我得到一个黑屏,我在控制台中获得以下信息: JSONArray无法转换为JSONObject错误

数据正在下载,我可以在控制台中看到它。

我在哪里错了?

5 个答案:

答案 0 :(得分:0)

活动并获取JSON

public class MainActivity extends ActionBarActivity {
CustomListAdapter adapter;
ListView mListView;
final static String URL = "http://hmkcode.appspot.com/jsonservlet";
ArrayList<Model> resModel = new ArrayList<>();
ProgressBar bar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mListView = (ListView) findViewById(R.id.list);
    bar = (ProgressBar) findViewById(R.id.bar);
    getResponse();


    adapter = new CustomListAdapter(this, resModel);

    mListView.setAdapter(adapter);

}

private void getResponse() {
    bar.setVisibility(View.VISIBLE);
    String tag_json_obj = "getresponse";
    JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
            URL, null, new com.android.volley.Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            Log.d("Response", response.toString());
            try {
                JSONArray feedArray = response.getJSONArray("feed");
                Model[] model = new Gson().fromJson(feedArray.toString(), Model[].class);
                Collections.addAll(resModel, model);
                adapter.addItems(resModel);
                bar.setVisibility(View.GONE);
                mListView.setVisibility(View.VISIBLE);
            } catch (JSONException e) {
                Log.e("Error", e.getMessage());
            }
        }
    }, new com.android.volley.Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d("Error: " + error.getMessage());
        }
    }) {
        @Override
        public String getBodyContentType() {
            return "application/json; charset=utf-8";
        }

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            return getRequestHeaders();
        }
    };
    AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
}


public static HashMap<String, String> getRequestHeaders() {
    HashMap<String, String> requestHeader = new HashMap<String, String>();
    String requestUsername = "user_name";
    String requestPassword = "password";
    String creds = String.format("%s:%s", requestUsername, requestPassword);
    String auth = "Basic " + Base64.encodeToString(creds.getBytes(), Base64.DEFAULT);
    requestHeader.put("Authorization", auth);
    requestHeader.put("Content-Type", "application/json; charset=utf-8");
    return requestHeader;
}

ListAdapter

public class CustomListAdapter extends BaseAdapter {
LayoutInflater inflater;
ImageLoader mImageLoader;
Context mContext;
ArrayList<Model> result;


public CustomListAdapter(Context context, ArrayList<Model> results) {
    mContext = context;
    result = results;
    inflater = LayoutInflater.from(context);
    mImageLoader = ImageLoader.getInstance();
}

@Override
public int getCount() {
    return result.size();
}

@Override
public Object getItem(int position) {
    return result.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    ViewHolder holder;
    final Model modit = result.get(position);
    if (convertView == null) {
        holder = new ViewHolder();
        convertView = inflater.inflate(R.layout.list_item, parent, false);
        // Initialize all attribiutes
        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    final ViewHolder holder1 = holder;
    // set values
    return convertView;
}

public void clearItems() {
    result.clear();
}

public void addItems(ArrayList<Model> rrespo) {
    result.addAll(rrespo);
    notifyDataSetChanged();
}

static class ViewHolder {
    ImageView picture;
    TextView title;
    TextView about;
    TextView dateTime;
}
}

这是你的模特

public class Model implements Serializable {
private String name;
private String country;
private String twitter;

public String getTwitter() {
    return twitter;
}

public void setTwitter(String twitter) {
    this.twitter = twitter;
}

public String getCountry() {
    return country;
}

public void setCountry(String country) {
    this.country = country;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}
}

创建XML布局并放置值

答案 1 :(得分:0)

  

JSONArray无法转换为JSONObject错误

因为返回的响应字符串是JSONObject的 JSONArray 而不是JSONObject的。

因此,需要将<ul> <li>item</li> <li>item</li> <li>item</li> <li>item</li> <li>item</li> <li>item</li> </ul>字符串转换为jsonStr而不是JSONArray。 变化:

JSONObject

JSONObject jsonObj = new JSONObject(jsonStr);

现在从JSONArray jsonArr = new JSONArray(jsonStr); for (int i = 0; i < jsonArr.length(); i++) { JSONObject c = jsonArr.getJSONObject(i); ..... } 获取所有JSONObject。

答案 2 :(得分:0)

您的字符串为JSONArray,因此将其解析为JSONObject会出错。更好的使用方式:

JSONArray contacts = new JSONArray(jsonStr);
for(int i=0; i<contacts.length(); i++) {
    //your code
}

答案 3 :(得分:0)

JSONObject jsonObj = new JSONObject(jsonStr);

jsonStr是一个数组,而不是一个对象,所以你必须创建一个JSONArray而不是一个JSONObject来创建根

答案 4 :(得分:0)

1.在获得每个索引的jsonobject之后,从jsonString创建JsonArray。
2.使用密钥参数

的Jsonobject到getString