Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.PrintWriter;
- import org.json.simple.JSONArray;
- import org.json.simple.JSONObject;
- import org.json.simple.parser.JSONParser;
- import org.json.simple.parser.ParseException;
- public class JSONDemo {
- public final static String FILE_NAME = "JSONDemo2.json";
- public static void main(String[] args) {
- jsonToFile(FILE_NAME);
- String jsonString = jsonFromFile(FILE_NAME);
- jsonParse(jsonString);
- }
- @SuppressWarnings("unchecked")
- public static void jsonToFile(String fileName) {
- String name = Svetovid.in.readLine("Enter a name: ");
- JSONObject root = new JSONObject();
- root.put("name", name);
- JSONArray courses = new JSONArray();
- while(true) {
- String course = Svetovid.in.readLine("Enter a course name (Enter to exit): ");
- if (course.length() == 0)
- break;
- int grade = Svetovid.in.readInt("Enter a course grade: ");
- JSONObject courseObject = new JSONObject();
- courseObject.put("grade", grade);
- courseObject.put("course", course);
- courses.add(courseObject);
- }
- root.put("courses", courses);
- File file = new File(fileName);
- try (PrintWriter writer = new PrintWriter(file)) {
- writer.print(root.toJSONString());
- } catch (FileNotFoundException e) {
- System.err.println(e.toString());
- }
- System.out.println("File created successfully.\n");
- }
- public static String jsonFromFile(String fileName) {
- StringBuilder jsonIn = new StringBuilder();
- while (Svetovid.in(fileName).hasMore()) {
- jsonIn.append(Svetovid.in(fileName).readLine());
- }
- return jsonIn.toString();
- }
- public static void jsonParse(String jsonString) {
- JSONParser parser = new JSONParser();
- try {
- JSONObject root = (JSONObject) parser.parse(jsonString);
- System.out.printf("Course info for %s", root.get("name") + "\n");
- JSONArray courses = (JSONArray) root.get("courses");
- for (int i = 0; i < courses.size(); i++) {
- JSONObject course = (JSONObject) courses.get(i);
- System.out.printf("course: %s", course.get("course") + ", ");
- System.out.printf("grade: %d", course.get("grade"));
- System.out.println();
- }
- } catch (ParseException e) { System.err.println(e); }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement