解析JSON以显示错误消息

时间:2013-09-02 00:50:54

标签: java android json web-services

我想添加一个toast消息,并在我的WEBSERVICE没有返回数据时将用户返回到主活动,并允许我解释更多。当用户搜索查询时,webservice将数据返回到我的JSON字符串,如下所示。

08-30 00:36:07.917: D/JSON String(1891): {
08-30 00:36:07.917: D/JSON String(1891): "all" :    {
08-30 00:36:07.917: D/JSON String(1891):    "count" : 25,
08-30 00:36:07.917: D/JSON String(1891):    "questions" : [     {   
08-30 00:36:07.917: D/JSON String(1891):            "Id" : "20100728112033AAb4hTA",
08-30 00:36:07.917: D/JSON String(1891):            "Subject" : "What is the oldest a bitch can more or less safely breed?",
08-30 00:36:07.917: D/JSON String(1891):            "Content" : "Don't worry I'm not going to breed - both my bitches are getting neutered in the next year, as is my dog! Just that me and a friend were talking about it after talking to the man who gave me Misty (my border collie) who said she could still breed at 7 - I thought the oldest was 5?\n",
08-30 00:36:07.917: D/JSON String(1891):            "Date" : "2010-07-28 18:20:33",
08-30 00:36:07.917: D/JSON String(1891):            "Timestamp" : "1280341233",
08-30 00:36:07.917: D/JSON String(1891):            "Link" : "http://answers.yahoo.com/question/?qid=20100728112033AAb4hTA",
08-30 00:36:07.917: D/JSON String(1891):            "Type" : "Answered",
08-30 00:36:07.917: D/JSON String(1891):            "CategoryId" : 396546021,
08-30 00:36:07.917: D/JSON String(1891):            "CategoryName" : "Dogs",
08-30 00:36:07.917: D/JSON String(1891):            "UserId" : "cP16Ctgxaa",
08-30 00:36:07.917: D/JSON String(1891):            "UserNick" : "Kiko",
08-30 00:36:07.917: D/JSON String(1891):            "UserPhotoURL" : "http://l.yimg.com/dg/users/1t1USxJpxAAEBQOGZjBMW0-5Wp_EG.medium.jpg",
08-30 00:36:07.917: D/JSON String(1891):            "NumAnswers" : 8,
08-30 00:36:07.917: D/JSON String(1891):            "NumComments" : 0,
08-30 00:36:07.917: D/JSON String(1891):            "ChosenAnswer" : "You just \"imagined\" that ,dear...not \"thought\". & your imagination is WRONG.\r\n\r\n9 or even 10,for a healthy TOP-PRODUCING bitc-h.\r\n\r\n\r\n\r\n*&* bitches are SPAYED & dogs are CASTRATED......big scary correct ADULT words.",
08-30 00:36:07.917: D/JSON String(1891):            "ChosenAnswererId" : "clN6YITvaa",
08-30 00:36:07.917: D/JSON String(1891):            "ChosenAnswererNick" : "Debunker",
08-30 00:36:07.917: D/JSON String(1891):            "ChosenAnswerTimestamp" : "1280317077",
08-30 00:36:07.917: D/JSON String(1891):            "ChosenAnswerAwardTimestamp" : "1280835336"
08-30 00:36:07.917: D/JSON String(1891):        },      {

这是我的代码,我将如何解析这些数据以获取我想要的特定数据

protected String doInBackground(String... args) {

    try {
        Intent in = getIntent();
        String searchTerm = in.getStringExtra("TAG_SEARCH");
        String query = URLEncoder.encode(searchTerm, "utf-8");
        String URL = "http://example.com";
        JSONParsser jParser = new JSONParsser();
        JSONObject json = jParser.readJSONFeed(URL);
        try {

            JSONArray questions = json.getJSONObject("all").getJSONArray("questions");

            for(int i = 0; i < questions.length(); i++) {
                JSONObject question = questions.getJSONObject(i);


            String Subject = question.getString(TAG_QUESTION_SUBJECT);
            String ChosenAnswer = question.getString(TAG_QUESTION_CHOSENANSWER);
            String Content = question.getString(TAG_QUESTION_CONTENT);


            }


        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

        return TAG_QUESTION ;           

}

但是当用户搜索查询并且webservice没有返回任何结果时,我的意思是Web服务数据已经"count" : 0,,并且在我的JSON字符串中看起来像这样。

09-02 00:25:55.466: D/JSON String(882): {
09-02 00:25:55.466: D/JSON String(882): "all" : {
09-02 00:25:55.466: D/JSON String(882):     "count" : 0,
09-02 00:25:55.466: D/JSON String(882):     "questions" : [     ]
09-02 00:25:55.466: D/JSON String(882):     }
09-02 00:25:55.466: D/JSON String(882): }

当发生这种情况时,我想要弹出一个Toast消息并将用户返回到主活动但是我只是不知道如何在返回计数0时解析该数据。我已经知道我需要添加一个{此位置的{1}}语句

if

我需要知道如何解析 try { // if statement here JSONArray questions = json.getJSONObject("all").getJSONArray("questions"); for(int i = 0; i < questions.length(); i++) { JSONObject question = questions.getJSONObject(i); String Subject = question.getString(TAG_QUESTION_SUBJECT); String ChosenAnswer = question.getString(TAG_QUESTION_CHOSENANSWER); String Content = question.getString(TAG_QUESTION_CONTENT); 以便我可以显示toast消息,然后将用户返回到主活动。希望你在这里看到我的想法,让我知道你是否有任何麻烦试图理解我的意思。 附:如果你想知道"count" : 0,是什么,它只是我用来连接到网络服务的类,JSONParsser只是传递searchTerm并对其进行编码。

editText

更新

@Override
protected void onPostExecute(String file_URL) { 

    if(file_URL.equals("0")) { 
        pDialog.dismiss();
        Toast.makeText(ListView.this, "No data found", Toast.LENGTH_SHORT).show();
        finish();    

}else{

        if (pDialog.isShowing()) pDialog.dismiss();
        ListAdapter adapter = new SimpleAdapter(getBaseContext(), questionList,
                R.layout.listelements,
                new String[] { TAG_QUESTION_SUBJECT }, new int[] {
                R.id.Subject,});

        setListAdapter(adapter);
}

3 个答案:

答案 0 :(得分:2)

要获取count值,只需执行

int count = json.getJSONObject("all").getInt("count");

(您应该像使用代码中的其他"count"一样用最终变量替换JSONObject

然后在执行

之前添加if
JSONArray questions = json.getJSONObject("all").getJSONArray("questions");

但您无法在doInBackground方法中显示吐司,您必须返回结果(字符串)并将其显示在onPostExecute()中。到目前为止,您没有返回正确的值,返回TAG_QUESTION,它必须是最终的String,这意味着您的处理结果永远不会在方法之外使用。

<强>更新

我认为你应该这样做:

首先,您不应该在doInBackground()中进行所有处理。在这个方法中,你应该只检索你的json,返回它并在onPostExecute()中处理它。为此,您需要更改AsyncTask,使其看起来像这样(注意最后一个参数的变化,从StringJSONObject):

private class yourAsyncTask extends AsyncTask<String, Void, JSONObject> {

这会告诉您的程序doInBackground()的返回值为JSONObject类型。因此,您接下来要做的就是更改doInBackground(),使其看起来像那样(再次注意返回值的变化,从StringJSONObject

protected JSONObject doInBackground(String... args) {
    JSONObject json = new JSONObject();
    try {
        Intent in = getIntent();
        String searchTerm = in.getStringExtra("TAG_SEARCH");
        String query = URLEncoder.encode(searchTerm, "utf-8");
        String URL = "http://example.com";
        JSONParsser jParser = new JSONParsser();

        try {
            json = jParser.readJSONFeed(URL);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return json;           

}

然后将onPostExecute()中参数的类型更改为JSONObject,并在检查count值后进行处理:

@Override
protected void onPostExecute(JSONObject json) { 

    int count = json.getJSONObject("all").getInt("count");
    if(count>0) {   // There are some questions to retrieve

        /*  In this part I just copied what you put in your question, 
            I don't know what your goal is so I can't help much, 
            but you have the logic to do so */

        JSONArray questions = json.getJSONObject("all").getJSONArray("questions");

        for(int i = 0; i < questions.length(); i++) {
            JSONObject question = questions.getJSONObject(i);


        String Subject = question.getString(TAG_QUESTION_SUBJECT);
        String ChosenAnswer = question.getString(TAG_QUESTION_CHOSENANSWER);
        String Content = question.getString(TAG_QUESTION_CONTENT);

        if (pDialog.isShowing()) pDialog.dismiss();
        ListAdapter adapter = new SimpleAdapter(getBaseContext(), questionList,
            R.layout.listelements,
            new String[] { TAG_QUESTION_SUBJECT }, new int[] {
            R.id.Subject,});

        setListAdapter(adapter);

    } else {

        Toast.makeText(ListView.this, "No data found", Toast.LENGTH_SHORT).show();
        finish();    

    }

}

答案 1 :(得分:1)

通过这种方式,您可以检查对象是否可用(假设在没有问题的情况下计数返回0)

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class Test {
    static String str = "{" + 
        "\"all\" : {" + 
        "    \"count\" : 0," + 
        "    \"questions\" : [     ]" + 
        "    }" + 
        "}";

public static void main(String[] args) {
    // TODO Auto-generated method stub
    try {

                  JsonParser jsonParser = new JsonParser();
                  JsonObject jsonString = (JsonObject)jsonParser.parse(str);
                  JsonObject allObj = jsonString.getAsJsonObject("all");

                  int quesCount = allObj.get("count").getAsInt();
                  if(quesCount == 0){
                  System.out.println("No Object Available as Object Count is : "+quesCount);
                }
      } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

}

答案 2 :(得分:0)

这样做

protected String doInBackground(String... args) {

    try {
        Intent in = getIntent();
        String searchTerm = in.getStringExtra("TAG_SEARCH");
        String query = URLEncoder.encode(searchTerm, "utf-8");
        String URL = "http://example.com";
        JSONParsser jParser = new JSONParsser();
        JSONObject json = jParser.readJSONFeed(URL);
        try {
            if(Integer.parseInt(data.getJSONObject("all").getString("count"))<=0){ //UPDATE HERE
            return "0";
        }
            JSONArray questions = json.getJSONObject("all").getJSONArray("questions");

            for(int i = 0; i < questions.length(); i++) {
                JSONObject question = questions.getJSONObject(i);


            String Subject = question.getString(TAG_QUESTION_SUBJECT);
            String ChosenAnswer = question.getString(TAG_QUESTION_CHOSENANSWER);
            String Content = question.getString(TAG_QUESTION_CONTENT);


            }


        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

        return TAG_QUESTION ;           

}


@Override
            protected void onPostExecute(String result) {
                super.onPostExecute(result);
                if(result==null || result.equals("0")){
                     Toast.makeText(ActivityName.this, "No data found", Toast.LENGTH_SHORT).show();
                }

            }