-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathJsonFormatStrategy.java
More file actions
72 lines (60 loc) · 2.71 KB
/
JsonFormatStrategy.java
File metadata and controls
72 lines (60 loc) · 2.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class JsonFormatStrategy implements FileFormatStrategy {
@Override
public ArrayList<Question> loadQuestions(String filePath) {
ArrayList<Question> questions = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
StringBuilder jsonContent = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
jsonContent.append(line);
}
// Simple JSON parsing (assuming a specific format)
String jsonString = jsonContent.toString();
jsonString = jsonString.replaceAll("[\\[\\]{}\"]", ""); // Remove brackets and quotes
String[] questionEntries = jsonString.split("},");
for (String entry : questionEntries) {
String[] parts = entry.split(",");
String category = "";
int value = 0;
String content = "";
String correctAnswer = "";
ArrayList<String> options = new ArrayList<>();
for (String part : parts) {
String[] keyValue = part.split(":");
if (keyValue.length < 2) continue;
String key = keyValue[0].trim();
String valueStr = keyValue[1].trim();
switch (key) {
case "category":
category = valueStr;
break;
case "value":
value = Integer.parseInt(valueStr);
break;
case "content":
content = valueStr;
break;
case "correctAnswer":
correctAnswer = valueStr;
break;
case "options":
String[] opts = valueStr.split(";");
for (String opt : opts) {
options.add(opt.trim());
}
break;
}
}
Question question = new Question(category, value, content, options, correctAnswer);
questions.add(question);
}
} catch (IOException e) {
System.err.println("Error loading JSON file: " + e.getMessage());
}
return questions;
}
}