[英]Reading JSON double dimensional array in Java
Each news
entry has three things : title
, content
and date
. 每个news
条目都有三个内容: title
, content
和date
。
The entries are retrieved from a database and I would like to read them in my application using JSONObject and JSONArray. 从数据库中检索条目,我想在我的应用程序中使用JSONObject和JSONArray读取它们。 However, I do not know how to use these classes. 但是,我不知道如何使用这些类。
Here is my JSON string: 这是我的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"
}
}
]
Your JSON string is a JSONArray
of JSONObject
which then contain an inner JSONObject
called "news". 您的JSON字符串是JSONObject
的JSONArray
,然后包含一个名为“news”的内部JSONObject
。
Try this for parsing it: 试试这个来解析它:
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 */
}
First of all, your JSON structure is not ideal. 首先,您的JSON结构并不理想。 You have an array of objects, with each object having a single object in it. 你有一个对象数组,每个对象都有一个对象。 However, you could read it like this: 但是,你可以这样读:
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");
}
However! 然而!
You could do better if you change your JSON to look like the following: 如果将JSON更改为如下所示,则可以做得更好:
[
{
"title": "5th title",
"content": "5th content",
"date": "1363197493"
},
{
"title": "4th title",
"content": "4th content",
"date": "1363197454"
}
]
Then, you could parse it as follows: 然后,您可以解析它如下:
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");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.