JSON Parser异常:Value ..无法转换为JSONObject

时间:2014-01-20 02:22:43

标签: android json parsing

这是我的JSONParser.java类

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();           

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        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();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

这是我的MainActivity.java

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class MainActivity extends ListActivity {

// url to make request
private static String url = 
"https://api.themoviedb.org/3/genre/list?api_key=d397dd2d354f088c6f0eb91c6b160bb0";

// JSON Node names
private static final String TAG_CONTACTS = "genre";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";

// contacts JSONArray
JSONArray genre = null;

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

    // Hashmap for ListView
    ArrayList<HashMap<String, String>> contactList = new     ArrayList<HashMap<String, String>>();

    // Creating JSON Parser instance
    JSONParser jParser = new JSONParser();

    // getting JSON string from URL
    JSONObject json = jParser.getJSONFromUrl(url);

    try {
        // Getting Array of Contacts
        genre = json.getJSONArray(TAG_CONTACTS);

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

            // Storing each json item in variable
            String id = c.getString(TAG_ID);
            String name = c.getString(TAG_NAME);

            // Phone number is agin JSON Object
            // JSONObject phone = c.getJSONObject(TAG_PHONE);
            // String mobile = phone.getString(TAG_PHONE_MOBILE);
            // String home = phone.getString(TAG_PHONE_HOME);
            // String office = phone.getString(TAG_PHONE_OFFICE);

            // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();

            // adding each child node to HashMap key => value
            map.put(TAG_ID, id);
            map.put(TAG_NAME, name);

            // adding HashList to ArrayList
            contactList.add(map);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    /**
     * Updating parsed JSON data into ListView
     * */
    ListAdapter adapter = new SimpleAdapter(this, contactList,
            R.layout.activity_main, new String[] { TAG_NAME, TAG_ID },
            new int[] { R.id.name, R.id.uid });

    setListAdapter(adapter);

    // selecting single ListView item
    ListView lv = getListView();
    lv.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick1(AdapterView<?> parent, View view,
                int position, long id) {
            // getting values from selected ListItem
            String name = ((TextView) view.findViewById(R.id.name))
                    .getText().toString();
            String cobaid = ((TextView) view.findViewById(R.id.uid))
                    .getText().toString();
            // Starting new intent
        //  Intent in = new Intent(getApplicationContext(),
        //  SingleMenuItemActivity.class);
        //  in.putExtra(TAG_NAME, name);
        //  in.putExtra(TAG_ID, id);
        //  startActivity(in);
        }

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            // TODO Auto-generated method stub

        }
    });
}

}

这是我的json格式

{"genres":[{"id":28,"name":"Action"},{"id":12,"name":"Adventure"},    {"id":16,"name":"Animation"},{"id":35,"name":"Comedy"},{"id":80,"name":"Crime"},{"id":105,"name":"Disaster"},{"id":99,"name":"Documentary"},{"id":18,"name":"Drama"},{"id":82,"name":"Eastern"},{"id":2916,"name":"Erotic"},{"id":10751,"name":"Family"},{"id":10750,"name":"Fan Film"},{"id":14,"name":"Fantasy"},{"id":10753,"name":"Film Noir"},{"id":10769,"name":"Foreign"},{"id":36,"name":"History"},{"id":10595,"name":"Holiday"},{"id":27,"name":"Horror"},{"id":10756,"name":"Indie"},{"id":10402,"name":"Music"},{"id":22,"name":"Musical"},{"id":9648,"name":"Mystery"},{"id":10754,"name":"Neo-noir"},{"id":1115,"name":"Road Movie"},{"id":10749,"name":"Romance"},{"id":878,"name":"Science Fiction"},{"id":10755,"name":"Short"},{"id":9805,"name":"Sport"},{"id":10758,"name":"Sporting Event"},{"id":10757,"name":"Sports Film"},{"id":10748,"name":"Suspense"},{"id":10770,"name":"TV movie"},{"id":53,"name":"Thriller"},{"id":10752,"name":"War"},{"id":37,"name":"Western"}]}

但是强制关闭,这是在LogCat

解析dataorg.json.JSONException时出错:不能将java.lang.String类型的值转换为JSONObject

你能帮忙解决一下源代码吗? 对不起,我是网络服务android的新手。我想从URL解析json

3 个答案:

答案 0 :(得分:1)

您已将此声明为

 private static final String TAG_CONTACTS = "genre";

在你的Json中

 {"genres":[{"id":28,"name":"Action"},{"id":12,"name":"Adventure"},    {"id":16,"name":"Animation"},{"id":35,"name":"Comedy"},{"id":80,"name":"Crime"},{"id":105,"name":"Disaster"},{"id":99,"name":"Documentary"},{"id":18,"name":"Drama"},{"id":82,"name":"Eastern"},{"id":2916,"name":"Erotic"},{"id":10751,"name":"Family"},{"id":10750,"name":"Fan Film"},{"id":14,"name":"Fantasy"},{"id":10753,"name":"Film Noir"},{"id":10769,"name":"Foreign"},{"id":36,"name":"History"},{"id":10595,"name":"Holiday"},{"id":27,"name":"Horror"},{"id":10756,"name":"Indie"},{"id":10402,"name":"Music"},{"id":22,"name":"Musical"},{"id":9648,"name":"Mystery"},{"id":10754,"name":"Neo-noir"},{"id":1115,"name":"Road Movie"},{"id":10749,"name":"Romance"},{"id":878,"name":"Science Fiction"},{"id":10755,"name":"Short"},{"id":9805,"name":"Sport"},{"id":10758,"name":"Sporting Event"},{"id":10757,"name":"Sports Film"},{"id":10748,"name":"Suspense"},{"id":10770,"name":"TV movie"},{"id":53,"name":"Thriller"},{"id":10752,"name":"War"},{"id":37,"name":"Western"}]}

因此 TAG_CONTACTS

的字符串声明中缺少 “s”

所以从

改变它
 private static final String TAG_CONTACTS = "genre";

private static final String TAG_CONTACTS = "genres";

答案 1 :(得分:0)

我们需要粘贴您的答案和堆栈跟踪的原始JSON。尽管嗅探你的代码,

  1. 你确定你的JSON有效吗?您可以使用以下方式进行验证:http://jsonlint.com

  2. JSONObject c = genre.getJSONObject(i);,您确定类型数组包含JSONObjects,而不是表示JSON的字符串吗?

  3. jObj = new JSONObject(json);,您确定json代表有效的JSON吗?

  4. 你确定TAG_ID对应的值是一个字符串类型,而不是长话吗? String id = c.getString(TAG_ID);可能是:long id = c.getLong(TAG_ID);

  5. 如果没有你的进一步帮助,很难得到更多帮助。

    编辑:根据您发表JSON格式的评论,您需要回答上面的第(3)点。您的id字段具有整数类型,而不是字符串类型。

答案 2 :(得分:0)

以这种方式实施。它可能对你有帮助..

 getJsonResponse(String url){
    try {
                JSONObject jObject = new JSONObject(url);
                    JSONArray list = jObject.getJSONArray("genres");

                    for (int i = 0; i < list.length(); i++) {
                        JSONObject element = list.getJSONObject(i);
    String id=element.getString("id);
    }
    }

}