JSON parsing in Java not finding items
I have the following JSON text to parse in Java:
{
"items": [
{
"key": "D033222DF44E5308482578EB0017588A",
"Date": "Aug 13 2011",
"Time": "04:54:46 PM",
"Company": "CHINA ESSENCE GROUP LTD.",
"AnnTitle": "FIRST QUARTER RESULTS * FINANCIAL STATEMENT AND RELATED ANNOUNCEMENT",
"Siblings": "18",
"SNo": 18
},
{
"key": "C9906046C7F0E232482578EB0030C437",
"Date": "Aug 13 2011",
"Time": "04:52:12 PM",
"Company": "DESIGjsonN STUDIO FURNITURE MFRLTD",
"AnnTitle": "NOTICE OF BOOK CLOSURE DATE FOR DIVIDEND",
"Siblings": "18",
"SNo": 17
}
]
}
Below is my JSONParser class:
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class JSONParser {
private String input = null;
public JSONParser() {
}
public JSONParser(String input) {
setInput(input);
}
public JSONArray parse() throws JSONException {
JSONObject obj = new JSONObject();
return obj.getJSONArray("items");
}
/**
* @return the input
*/
public String getInput() {
return input;
}
/**
* @param input the input to set
*/
public void setInput(String input) {
开发者_开发技巧 this.input = input;
}
}
My main() method class contains these codes to execute the parser to parse the "jsonStr" object:
JSONParser parser = new JSONParser(jsonStr);
JSONArray array = parser.parse();
for (int i = 0; i < array.length(); i++) {
Object obj = array.get(i);
System.out.println(">> " + obj.toString() + "\n");
}
My output shows:
SEVERE: null
org.json.JSONException: JSONObject["items"] not found.
I am using the json.org provided Java codes for JSON.
How should I parse the above string ?
Thanks.
You have not actually passed the input string to the JSON parsing library. The JSONParser#parse()
method needs to (somehow) use this.input
. Try this:
public JSONArray parse() throws JSONException
{
JSONObject obj = new JSONObject(this.input);
return obj.getJSONArray("items");
}
That said, org.json.JSONObject
is an ancient implementation. I would strongly encourage you to use a more modern JSON library, such as one of the following:
- JSON.simple
- Google GSON
- Jackson
精彩评论