Reputation: 3296
I created a JSON file and I uploaded on a domain, my goal is to parse that document e get back the informations but I do something wrong, this is my JSON file:
{
"Show" : {
"id" : "abcde123",
"name" : "Traviata",
"date" : "September 15, 2011"
}
}
This is the Java code that I use to parse the JSON:
private void parse(){
try {
URL eventsJSON = new URL("http://www.site.com/test/sample.json");
URLConnection tc = eventsJSON.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(tc.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
JSONArray jArray = new JSONArray(line);
for (int i = 0; i < jArray.length(); i++) {
eventsJSONObject = (JSONObject) jArray.get(i);
}
}
JSONArray eventsArray = eventsJSONObject.getJSONArray("Show");
//name of the show
Log.d("LOG", jArray.getJSONObject(0).getString("name").toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
But the class isn't working.. can someone help me please? Thanks!!!! :)
EDIT: This is a working code, but I can't make it work parsing the JSON from a file
String jString = "{\"Show\" : {\"from\" : \"June 12, 2011\",\"id\" : \"abcde123\",\"name\" : \"Traviata\"}}";
JSONObject jObject = new JSONObject(jString);
JSONObject eventsObject = jObject.getJSONObject("Shows");
String eventId = eventsObject.getString("id");
String eventName = eventsObject.getString("name");
String eventDateFrom = eventsObject.getString("from");
how do I implement the buffered reader and memorize the JSON code in the jString String?
Upvotes: 0
Views: 506
Reputation: 137382
This:
JSONArray eventsArray = eventsJSONObject.getJSONArray("Show");
should be parsed as JSONObject:
JSONObject eventObj = eventsJSONObject.getJSONOnject("Show");
Rest should be simple. "show" represents an object with 3 fields, not an array.
BTW, an array would look like that:
{
"Show" : [
"id" : "abcde123",
"name" : "Traviata",
"date" : "September 15, 2011"
]
}
Upvotes: 2