6

每个news条目包含三个内容:title和。contentdate

这些条目是从数据库中检索的,我想在我的应用程序中使用 JSONObject 和 JSONArray 读取它们。但是,我不知道如何使用这些类。

这是我的 JSON 字符串:

[
   {
      "news":{
         "title":"5th title",
         "content":"5th content",
         "date":"1363197493"
      }
   },
   {
      "news":{
         "title":"4th title",
         "content":"4th content",
         "date":"1363197454"
      }
   },
   {
      "news":{
         "title":"3rd title",
         "content":"3rd content",
         "date":"1363197443"
      }
   },
   {
      "news":{
         "title":"2nd title",
         "content":"2nd content",
         "date":"1363197409"
      }
   },
   {
      "news":{
         "title":"1st title",
         "content":"1st content",
         "date":"1363197399"
      }
   }
]
4

2 回答 2

8

您的 JSON 字符串是其中的一个JSONArrayJSONObject然后包含一个JSONObject名为“新闻”的内部。

试试这个来解析它:

JSONArray array = new JSONArray(jsonString);

for(int i = 0; i < array.length(); i++) {
    JSONObject obj = array.getJSONObject(i);
    JSONObject innerObject = obj.getJSONObject("news");

    String title = innerObject.getString("title");
    String content = innerObject.getString("content");
    String date = innerObject.getString("date");

    /* Use your title, content, and date variables here */
}
于 2013-03-14T14:18:42.680 回答
2

首先,您的 JSON 结构并不理想。您有一个对象数组,每个对象中都有一个对象。但是,您可以这样阅读:

JSONArray jsonArray = new JSONArray (jsonString);
int arrayLength = jsonArray.length ();

for (int counter = 0; counter < arrayLength; counter ++) {
    JSONObject thisJson = jsonArray.getJSONObject (counter);

    // we finally get to the proper object
    thisJson = thisJson.getJSONObject ("news");

    String title = thisJson.getString ("title");
    String content = thisJson.getString ("content");
    String date = thisJson.getString ("date");

}

然而!

如果您将 JSON 更改为如下所示,您可以做得更好:

[
    {
        "title": "5th title",
        "content": "5th content",
        "date": "1363197493"
    },
    {
        "title": "4th title",
        "content": "4th content",
        "date": "1363197454"
    }
]

然后,您可以按如下方式解析它:

JSONArray jsonArray = new JSONArray (jsonString);
int arrayLength = jsonArray.length ();

for (int counter = 0; counter < arrayLength; counter ++) {
        // we don't need to look for a named object any more
    JSONObject thisJson = jsonArray.getJSONObject (counter);    

    String title = thisJson.getString ("title");
    String content = thisJson.getString ("content");
    String date = thisJson.getString ("date");
}
于 2013-03-14T14:18:48.813 回答