0

我正在尝试解析 json 对象以将其填充到列表视图中,但我遇到了一些问题,请帮忙

我收到 NullpointerException

这是我的完整代码:

我正在从以下 url 解析数据

我正在解析的 URL 是

解析数据的代码

 public class JSONParser {

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

public JSONParser(){

}

public JSONObject getJSONFromUrl(String url){

//making Http request
try{
//default httpclient    
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;

}

}

here is activity code

public class AndroidJSONParsingActivity extends ListActivity {

// url to make request
private static String url = "http://www.kaverisoft.com/careers/assignments/android/a1.php";

// JSON NAme Node

private static final String TAG_BOOK = "book";
private static final String TAG_ID = "id";
private static final String TAG_TITLE = "title";
private static final String TAG_AUTHORS = "authors";
private static final String TAG_DESCRIPTION = "description";
private static final String TAG_PRICE = "price";


//Book JSONArray
JSONArray book = null;

@Override
public void onCreate(Bundle savedInstanceState) {


    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // HashMap for ListView

    ArrayList<HashMap<String, String>> bookList = 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 books

        book = json.getJSONArray(TAG_BOOK);

    // looping through all books

        for(int i=0;i<book.length();i++){

            JSONObject c = book.getJSONObject(i);


            // storing each json item in variable

            String title = c.getString(TAG_TITLE);
            String price = c.getString(TAG_PRICE);
            String authors = c.getString(TAG_AUTHORS);
            String id = c.getString(TAG_ID);
            String description = c.getString(TAG_DESCRIPTION);



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

            map.put(TAG_ID, id);
            map.put(TAG_TITLE, title);
            map.put(TAG_PRICE, price);
            map.put(TAG_AUTHORS, authors);
            map.put(TAG_DESCRIPTION, description);

            bookList.add(map);


        }

    }

        catch (JSONException e) {
            e.printStackTrace();    

        }

    // Updating Parsed Data into ListView

    ListAdapter adapter = new SimpleAdapter(this, bookList,
            R.layout.list_item,
            new String[]{TAG_TITLE,TAG_DESCRIPTION,TAG_AUTHORS } , new int[] {
            R.id.title,R.id.description,R.id.author });

setListAdapter(adapter);

// selecting single list view item

ListView lv = getListView();

 // Launching new screen on Selecting Single ListItem
    lv.setOnItemClickListener(new OnItemClickListener() {


        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // getting values from selected ListItem
            String title = ((TextView) view.findViewById(R.id.title)).getText().toString();
            String authors = ((TextView) view.findViewById(R.id.author)).getText().toString();
            String description = ((TextView) view.findViewById(R.id.description)).getText().toString();

            // Starting new intent
            Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
            in.putExtra(TAG_TITLE, title);
            in.putExtra(TAG_AUTHORS, authors);
            in.putExtra(TAG_DESCRIPTION, description);
            startActivity(in);

        }
    });



}

}

我正在尝试仅解析书籍对象

请解决我的问题。

LogCat 详细信息

08-24 00:56:48.202: W/dalvikvm(949): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
08-24 00:56:48.263: E/AndroidRuntime(949): FATAL EXCEPTION: main
08-24 00:56:48.263: E/AndroidRuntime(949): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.sree.androidjsonparser/com.sree.androidjsonparser.AndroidJSONParsingActivity}: java.lang.NullPointerException
08-24 00:56:48.263: E/AndroidRuntime(949):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
08-24 00:56:48.263: E/AndroidRuntime(949):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
08-24 00:56:48.263: E/AndroidRuntime(949):  at android.app.ActivityThread.access$2300(ActivityThread.java:125)
08-24 00:56:48.263: E/AndroidRuntime(949):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
08-24 00:56:48.263: E/AndroidRuntime(949):  at android.os.Handler.dispatchMessage(Handler.java:99)
08-24 00:56:48.263: E/AndroidRuntime(949):  at android.os.Looper.loop(Looper.java:123)
08-24 00:56:48.263: E/AndroidRuntime(949):  at android.app.ActivityThread.main(ActivityThread.java:4627)
08-24 00:56:48.263: E/AndroidRuntime(949):  at java.lang.reflect.Method.invokeNative(Native Method)
08-24 00:56:48.263: E/AndroidRuntime(949):  at java.lang.reflect.Method.invoke(Method.java:521)
08-24 00:56:48.263: E/AndroidRuntime(949):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
08-24 00:56:48.263: E/AndroidRuntime(949):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
08-24 00:56:48.263: E/AndroidRuntime(949):  at dalvik.system.NativeStart.main(Native Method)
08-24 00:56:48.263: E/AndroidRuntime(949): Caused by: java.lang.NullPointerException
08-24 00:56:48.263: E/AndroidRuntime(949):  at com.sree.androidjsonparser.AndroidJSONParsingActivity.onCreate(AndroidJSONParsingActivity.java:62)
08-24 00:56:48.263: E/AndroidRuntime(949):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
08-24 00:56:48.263: E/AndroidRuntime(949):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
08-24 00:56:48.263: E/AndroidRuntime(949):  ... 11 more
08-24 00:56:53.812: I/Process(949): Sending signal. PID: 949 SIG: 9
4

1 回答 1

1

您的问题在于您的 JSONParser..that 并且从该站点返回的 JSON 格式不正确。您有一堆 JSONObjects,其中包含具有相似名称的 JSONObjects。我制定了一个快速简便的解决方案来处理它,但如果您控制生成 JSON 的代码,那么我建议将项目类别(书籍、音乐、相机)分组到它们自己的 JSONArrays 中

您从网站返回的 JSON 是带有 JSONObjects 的 JSONArray。您正在执行以下操作

jObj = 新的 JSONObject(json);

你应该做

jObj = 新 JSONArray(json);

然后你需要改变你的回报是 JSONArray 而不是 JSONObject

然后在主要活动中将“json”更改为 JSONArray 并摆脱“book”..只需循环遍历 JSONArray

还要将您的尝试移动到循环内部。

JSONParser jParser = new JSONParser();

            // getting Json String from url

            JSONArray json = jParser.getJSONFromUrl(url);


                // getting array of books

               //Get rid of this = book = json.getJSONArray(TAG_BOOK);

            // looping through all books

                 for(int i=0;i<json.length();i++){
                try{
                JSONObject parent = json.getJSONObject(i);
                JSONObject c  = parent.optJSONObject("camera");
                if(c == null)
                    c = parent.optJSONObject("book");
                if(c == null)
                    c = parent.optJSONObject("music");
                // storing each json item in variable

                String title = c.getString(TAG_TITLE);
                String price = c.getString(TAG_PRICE);
                String authors = c.getString(TAG_AUTHORS);
                String id = c.getString(TAG_ID);
                String description = c.getString(TAG_DESCRIPTION);
                // creating new HashMap
                HashMap<String, String> map = new HashMap<String, String>();

                map.put(TAG_ID, id);
                map.put(TAG_TITLE, title);
                map.put(TAG_PRICE, price);
                map.put(TAG_AUTHORS, authors);
                map.put(TAG_DESCRIPTION, description);

                bookList.add(map);

            }

            catch (JSONException e) {
                e.printStackTrace();    

            }
            }

- - -编辑

正如我的评论中所建议的,您应该重做创建 JSON 输出的代码

简单来说,您需要一个包含每个“类别”的 JSONObjects 的主数组,然后这些类别中的每一个都将是 JSONArray 中的 JSONObject

JSON 应该如下所示

[
{ "camera" :
[
   {
   "picture":"http://qqq.com",
   "price":9.99
    },
 {
   "picture":"http://eee.com",
   "price":9.99
    }
]
},
{ "music" :
[
   {
   "picture":"http://aaa.com",
   "price":9.99
    },
 {
   "picture":"http://sss.com",
   "price":9.99
    }
]
},
{ "book" :
[
   {
   "picture":"http://fff.com",
   "price":9.99
    },
 {
   "picture":"http://ggg.com",
   "price":9.99
    }
]
}
]

这样,您可以为不同的类别执行不同的操作(如果需要),并将类别中的任何类似 JSON 对象都组合在一起。

或者,如果无论是书、音乐还是相机,动作都是相同的,那么您可以在 JSON 对象中添加另一个字段以用于“类型”,然后在没有名称的数组 (JSON_array.put()) 中创建 JSONObject所以它会显示为

[
{
"type":"camera",
"picture":"http://img5.flixcart.com/image/camera/5/p/a/nikon-d90-slr-40x40-imacxmh3y6wmqh8b.jpeg",
"model":"D90 SLR with AF-S 18-105mm VR Kit Lens",
"make":"Nikon",
"price":57182.0
},
{
"type":"book",
"description":"This book is one of a series of texts written by faculty of the Electrical Engineering and Computer Science Department at the Massachusetts Institute of Technology. It was edited and produced by The MIT Press under a joint production-distribution arrangement with the McGraw-Hill Book Company.",
"authors":"Harold Abelson and Gerald Jay Sussman with Julie Sussman",
"price":469.0,
"id":51087,
"title":"Structure and Interpretation of Computer Programs"
}
]

同样,您应该采取的路线取决于您之后将如何处理数据

于 2012-08-23T19:32:53.977 回答