Skip to content

Instantly share code, notes, and snippets.

@Phoenix-Effect
Created July 3, 2018 01:03
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Phoenix-Effect/58157b6f7b554ba27d3aac660737f9d0 to your computer and use it in GitHub Desktop.
Save Phoenix-Effect/58157b6f7b554ba27d3aac660737f9d0 to your computer and use it in GitHub Desktop.
Example of how you can read and parse JSON file in Java. Requires JSON library.
import org.json.*;
import java.io.*;
public class main {
public static JSONObject obj;
public static void main(String args[]){
try {
obj = new JSONObject( fileToString("src/main/resources/questions.json") );
JSONArray questionsArray = obj.getJSONArray("question");
for(int i = 0; i < questionsArray.length(); i++){
System.out.println((i+1) + ") " + questionsArray.getJSONObject(i).getString("questionText"));
if(questionsArray.getJSONObject(i).getString("type").equals("mcq")){
JSONArray answersArray = questionsArray.getJSONObject(i).getJSONArray("options");
for(int x = 0; x < answersArray.length(); x++){
System.out.println(" " + (x+1) + ") " + answersArray.get(x));
}
}
System.out.println();
System.out.println("Answer is: " + questionsArray.getJSONObject(i).getString("answer"));
System.out.println("-----------------");
System.out.println();
}
} catch(Exception e){
System.out.println("Error building JSON");
}
}
private static String fileToString(String fileName){
String str = "";
try {
InputStream is = new FileInputStream(fileName);
BufferedReader buf = new BufferedReader(new InputStreamReader(is));
String line = buf.readLine();
StringBuilder sb = new StringBuilder();
while (line != null) {
sb.append(line).append("\n");
line = buf.readLine();
}
String fileAsString = sb.toString();
return fileAsString;
} catch(Exception e){
System.out.println("Error");
}
return str;
}
}
{
"question": [
{
"questionText": "What is the best programming language",
"options": [
"php",
"java",
"c++"
],
"answer": "php",
"type": "mcq"
},
{
"questionText": "Favourite cheese",
"options": [
"gouda",
"goat",
"parmesian"
],
"answer": "gouda",
"type": "mcq"
},
{
"questionText": "My name is ______",
"answer": "zach",
"type": "fib"
}
]
}
@jonathasrochadesouza
Copy link

Thank you brother! You helped me a lot! 👍

@garpoz
Copy link

garpoz commented Apr 19, 2022

mer30

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment