1

我在这里需要一点帮助,就像一点建议一样。我需要一双额外的眼睛来查看我的代码并查看我解析的 Yahoo Answers JSON 数据是否存在错误。我认为我错误地解析了 JSON 数据,我只是希望有人查看它以确保我解析了正确的数据。

这是我试图从我的网络服务中解析的数据:

{
 "query": {
  "count": 1,
  "created": "2013-08-09T19:37:46Z",
  "lang": "en-US",
  "diagnostics": {
   "publiclyCallable": "true",
   "url": {
    "execution-start-time": "524",
    "execution-stop-time": "783",
    "execution-time": "259",
    "proxy": "DEFAULT",
    "content": "http://answers.yahooapis.com/AnswersService/V1/getQuestion?question_id=20100207231859AAZVura"
   },
   "user-time": "783",
   "service-time": "259",
   "build-version": "38788"
  },
  "results": {
   "Question": {
    "id": "20100207231859AAZVura",
    "type": "Answered",
    "Subject": "What gives some humans the idea that you cannot prove a negative?",
    "Content": "Seriously, humans, what is this nonsense?  For one thing, the statement 'You cannot prove a negative' is itself phrased negatively.  So if it's true, how could you possibly know?\n\nBut more to the point, a negative claim can be disproved in precisely the same ways as a positive claim.  Let's take something clearly false as an example, yes?  So, square circles.  If I say that there is a shape that is both a square and a circle, you can disprove my claim (that is, you can prove the negative claim that there is no such shape) by demonstrating that the property of being square contradicts the property of being circular.  Simple, yes?\n\nSo what's the deal?  Please explain using words that a clock can understand.\nAonghas, that is true only if the metaphysical things in question have no connection to the physical world.  A god who is said to have done things on Earth can be disproved by establishing that those things did not happen, for example.\n\nHuliendin, just because the truth value of a statement may change does not mean that it does not have one at any given point in time.\n\nDavid, a square is defined as a shape with particular characteristics.  If a shape does not have those characteristics, it is not a square.  It is not possible to discover a square that does not fit the definition of a square.  The same goes for a circle.  And since the two definitions contradict each other, a shape cannot fit both.\n\nRyan, many humans certainly do have ideas about the properties a god would have.  They've written books attributing certain propreties to gods.\nWilliam, you misunderstand the nature of my example.  It doesn't matter whether I have seen one.  The fact is that if one did exist, it would have to fit the definition of a square and it would have to fit the definition of a circle.  That means that, for example, it would have to have exactly one side and exactly four sides.  That is a contradiction, and it is a fundamental assumption of logic that a contradictory statement must be false.\nBloodzwurth, you have trouble proving that because you're being deliberately vague.  It has nothing to do with negativity.  You would have exactly the same difficulty trying to prove that claim to be true as you would trying to prove it to be false.\nI didn't know you spoke clock, CAt.  Anyway I agree with you, but only in respect to a posteriori arguments.\nHuliendin, you are treating my proof as an inductive argument, which it is not.  I am not saying that no squares are also circles because we haven't come across any yet.\n\nLet's put it this way.\n1. If x is a square, then x has straight sides. (That is part of the definition of a square, and so this statement is tautologous and hence must be correct.)\n2. If x is a circle, then x does not have straight sides. (Again, just part of the definition.)\n3. x is both a circle and a square. (Assumed premise.)\n4. x has straight sides (from 1 and 3).\n5. x does not have straight sides (from 2 and 3).\n6. x does and does not have straight sides (from 4 and 5).\n7. x is not both a square and a circle (from 3 and 6, reductio ad absurdum).\n\nSee?  Simple deductive logic.  This proof works for any shape 'x' regardless of whether it has been found or not.  What I have demonstrated is not just that a square circle does not exist, but that a square circle cannot exist.\n",
    "Date": "2010-02-07 23:18:59",
    "Timestamp": "1265584739",
    "Link": "http://answers.yahoo.com/question/?qid=20100207231859AAZVura",
    "Category": {
     "id": "396545163",
     "content": "Religion & Spirituality"
    },
    "UserId": "v2w0u1XAaa",
    "UserNick": "Yellow Alarm Clock",
    "UserPhotoURL": "http://socialprofiles.zenfs.com/images/a3b93240efb619ea3d1b5e2e90844784_48.jpg",
    "NumAnswers": "9",
    "NumComments": "2",
    "ChosenAnswer": "Words a clock can understand huh? Hmmm\n \nOk\n\nTic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc  tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic toc tic t",
    "ChosenAnswererId": "FWZentXQaa",
    "ChosenAnswererNick": "The CAt in the Tin Foil HAt v21",
    "ChosenAnswerTimestamp": "1265585654",
    "ChosenAnswerAwardTimestamp": "1265757240",
    "Answers": {
     "Answer": [
      {
       "Content": "It doesn't matter if you're talking about metaphysical matters (the existence of gods, the afterlife, spirits, whatever), because there's no evidence for or against metaphysical things. Unless you count the lack of evidence as evidence of absence (and some people do, and some people don't).\n\nThe whole point of the matter is that people should just stop worrying about religious/spiritual stuff and just get on with their lives.",
       "Reference": null,
       "Best": null,
       "UserId": "DrMxELRraa",
       "UserNick": "Aonghas M",
       "Date": "2010-02-07 23:22:28",
       "Timestamp": "1265584948"
      },

主要活动:

public class MainActivity extends Activity {

    Button getanswer;  

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

        Button getanswer = (Button) findViewById(R.id.button1);
        getanswer.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {       
            EditText et = (EditText) findViewById(R.id.editText1);
            String searchTerm = et.getText().toString().trim();         
            Intent in = new Intent(MainActivity.this, ListView.class);
            in.putExtra("TAG_SEARCH", searchTerm);
            startActivity(in);
        }

        });
    }}

这是我尝试从 Web 服务解析数据的方式:

public class ListView extends ListActivity {    


    ArrayList<HashMap<String, String>> questionList;        

     final String TAG_RESULTS = "results";
     final String TAG_QUESTION_SUBJECT = "Subject";
     final String TAG_QUESTION_NUMANSWERS = "NumAnswers";
     final String TAG_QUESTION = "question";
     final String TAG_QUESTION_CONTENT = "Content";
     final String TAG_QUESTION_CHOSENANSWER = "ChosenAnswer";
     final String TAG_ANSWERS = "answers";
     final String TAG_ANSWER = "answer";    
     final String TAG_ANSWERS_CONTENT = "content";      
     final String TAG_QUERY = "query";

            JSONArray question = null;          

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




      new LoadAllData().execute();
        }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == 100) {
            Intent intent = getIntent();
            startActivity(intent);
            finish();
        }
    }

    class LoadAllData extends AsyncTask<String, String, String> {


        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            ProgressDialog pDialog; 
            pDialog = new ProgressDialog(ListView.this);
            pDialog.setMessage("Loading Data. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
            if (pDialog != null && pDialog.isShowing()) pDialog.dismiss();

        }

        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 {
                    //question = json.getJSONArray(TAG_QUESTION);


                    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 NumAnswers = question.getString(TAG_QUESTION_NUMANSWERS);
                    String ChosenAnswer = question.getString(TAG_QUESTION_CHOSENANSWER);
                    String Content = question.getString(TAG_QUESTION_CONTENT);

                    JSONArray answers = question.getJSONObject(TAG_ANSWERS).getJSONArray(TAG_ANSWER);


                    JSONObject answer = answers.getJSONObject(0);

                    String content = answer.getString(TAG_ANSWERS_CONTENT);

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

                               map.put(TAG_QUESTION_SUBJECT, Subject);
                               map.put(TAG_QUESTION_NUMANSWERS, NumAnswers);

                               questionList.add(map);


                    }


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

                return TAG_QUESTION     ; 



        }
        protected void onPostExecute(String file_URL) {

                ListAdapter adapter = new SimpleAdapter(getBaseContext(), questionList,
                        R.layout.listview,
                        new String[] { TAG_QUESTION_SUBJECT, TAG_QUESTION_NUMANSWERS }, new int[] {
                        R.id.Subject, R.id.NumAnswers });

                setListAdapter(adapter);

                android.widget.ListView lv = getListView();

                lv.setOnItemClickListener(new OnItemClickListener() {

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

                    }   

                });     

        }}

    }

错误信息:

08-11 02:42:52.882: E/AndroidRuntime(4516): FATAL EXCEPTION: AsyncTask #1
08-11 02:42:52.882: E/AndroidRuntime(4516): java.lang.RuntimeException: An error occured while executing doInBackground()
08-11 02:42:52.882: E/AndroidRuntime(4516):     at android.os.AsyncTask$3.done(AsyncTask.java:299)
08-11 02:42:52.882: E/AndroidRuntime(4516):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
08-11 02:42:52.882: E/AndroidRuntime(4516):     at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
08-11 02:42:52.882: E/AndroidRuntime(4516):     at java.util.concurrent.FutureTask.run(FutureTask.java:239)
08-11 02:42:52.882: E/AndroidRuntime(4516):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
08-11 02:42:52.882: E/AndroidRuntime(4516):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
08-11 02:42:52.882: E/AndroidRuntime(4516):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
08-11 02:42:52.882: E/AndroidRuntime(4516):     at java.lang.Thread.run(Thread.java:856)
08-11 02:42:52.882: E/AndroidRuntime(4516): Caused by: java.lang.NullPointerException
08-11 02:42:52.882: E/AndroidRuntime(4516):     at com.theproblemsolver.ListView$LoadAllData.doInBackground(ListView.java:118)
08-11 02:42:52.882: E/AndroidRuntime(4516):     at com.theproblemsolver.ListView$LoadAllData.doInBackground(ListView.java:1)
08-11 02:42:52.882: E/AndroidRuntime(4516):     at android.os.AsyncTask$2.call(AsyncTask.java:287)
08-11 02:42:52.882: E/AndroidRuntime(4516):     at java.util.concurrent.FutureTask.run(FutureTask.java:234)
08-11 02:42:52.882: E/AndroidRuntime(4516):     ... 4 more

当我阅读 logcat 时,它给了我一个系统错误,说我的结果字符串没有价值。Web 服务将数据返回到我的 jObj 字符串,但不是我解析的太平洋数据。

4

4 回答 4

3

编辑 3:看起来您期望的 JSON 响应和实际响应具有不同的结构。尝试这个:

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

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

    String subject = question.getString("Subject");
    String numAnswers = question.getString("NumAnswers");
    String chosenAnswer = question.getString("ChosenAnswer");
    String content = question.getString("Content");
}

编辑 2:使用您发布的完整 JSON,您可以看到层次结构:

query -> results -> Question

Question节点包含您需要的所有信息。这是您获取它的引用的方式:

final String TAG_QUERY = "query";

JSONObject question = jObj.getJSONObject(TAG_QUERY)
    .getJSONObject(TAG_RESULTS)
    .getJSONObject(TAG_QUESTION);

从中,你可以得到你想要的数据(不需要循环,因为只有一个问题):

String subject = question.getString(TAG_QUESTION_SUBJECT);
String numAnswers = question.getString(TAG_QUESTION_NUMANSWERS);
String chosenAnswer = question.getString(TAG_QUESTION_CHOSENANSWER);
String content = question.getString(TAG_QUESTION_CONTENT);

JSONArray answers = question.getJSONObject(TAG_ANSWERS).getJSONArray(TAG_ANSWER);

// If you only want the first answer:
JSONObject answer = answers.getJSONObject(0);

String content = answer.getString(TAG_ANSWERS_CONTENT);

试试看,让我知道它是怎么回事!


编辑:你能复制并粘贴整个 JSON 响应吗?如果我们看不到 JSON 的结构,就无法帮助您。


在从 Yahoo Finance API 返回的 JSON 中,results节点不是数组,它是一个包含数组的对象:Question,这是您要查找的。试试下面的代码:

final String TAG_RESULTS = "results";
final String TAG_QUESTION_SUBJECT = "Subject";
final String TAG_QUESTION_NUMANSWERS = "NumAnswers";
final String TAG_QUESTION = "Question";
final String TAG_QUESTION_CONTENT = "Content";
final String TAG_QUESTION_CHOSENANSWER = "ChosenAnswer";
final String TAG_ANSWERS = "Answers";
final String TAG_ANSWER = "Answer";    
final String TAG_ANSWERS_CONTENT = "Content";      

JSONArray questions = jObj.getJSONObject(TAG_RESULTS).getJSONArray(TAG_QUESTION);

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

    String subject = question.getString(TAG_QUESTION_SUBJECT);
    String numAnswers = question.getString(TAG_QUESTION_NUMANSWERS);
    String chosenAnswers= question.getString(TAG_QUESTION_CHOSENANSWER);
    String content = question.getString(TAG_QUESTION_CONTENT);

    JSONObject answers = question.getJSONObject(TAG_ANSWERS);
    JSONObject answer = answers.getJSONObject(TAG_ANSWER);
    String Content = answers.getString(TAG_ANSWERS_CONTENT);
}
于 2013-08-10T17:14:49.473 回答
1

正如其中一个评论中已经建议的那样,您可以使用库更轻松地做到这一点GSON,您可以查看我写的本指南,了解它的用法以及使用该库和使用本机对象之间的区别,就像您现在所做的那样:

使用 Gson 和本机对象解析 JSON 文件

于 2013-08-11T00:30:41.823 回答
1

我建议看一下 gson 库,用于将 java 对象转换为 json,反之亦然。http://code.google.com/p/google-gson/

您可以使用序列化名称属性修饰的所有相关字段创建类,然后在一行代码中与 json 相互转换,而无需手动构建对象。

于 2013-08-10T17:29:07.913 回答
0

也许你应该为你必须创建的所有对象创建一个类,这会让你更容易......你应该尝试@Raman的帖子,但你可能想要获得所有答案的数组,而不是像这样的对象@Raman 是这么说的

JSONObject answers = question.getJSONObject(TAG_ANSWERS);

你可能想让它成为一个像这样的数组来循环它

JSONArray answers = question.getJSONArray(TAG_ANSWERS);
于 2013-08-10T18:32:13.533 回答