Java tutorial
package org.ESLM.Parser; /* Copyright (C) 2015 Rmi Even, Eric Perlinski <remi.even@telecomnancy.net> <eric.perlinski@telecomnancy.net> This file is part of ESLM. ESLM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ESLM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import java.io.Reader; import org.ESLM.Model.Instruction; import org.ESLM.Model.ProtoLesson; import org.json.JSONArray; import org.json.JSONObject; import org.json.JSONTokener; public class JSONProtoLessonParser { private Reader reader; private ProtoLesson parsedLesson; public JSONProtoLessonParser(Reader reader) { this.reader = reader; } public ProtoLesson getParsedLesson() throws BadFormedJSONExerciseException { if (parsedLesson == null) parseLesson(); return parsedLesson; } private void parseLesson() throws BadFormedJSONExerciseException { JSONTokener tokener = new JSONTokener(reader); JSONObject jsonLesson = new JSONObject(tokener); String title = jsonLesson.optString("title", "Untitled Lesson"); JSONArray jsonExercises = jsonLesson.optJSONArray("exercises"); Instruction[] exercises = parseExercises(jsonExercises); parsedLesson = new ProtoLesson(title); for (Instruction instruction : exercises) parsedLesson.addExercise(instruction); } private Instruction[] parseExercises(JSONArray jsonExercises) throws BadFormedJSONExerciseException { int numberOfExercises = jsonExercises.length(); Instruction[] instructions = new Instruction[numberOfExercises]; for (int i = 0; i < numberOfExercises; i++) { JSONObject jsonExercise = jsonExercises.getJSONObject(i); instructions[i] = ExerciseFactory.createInstruction(jsonExercise); } return instructions; } }