|
| 1 | +/* |
| 2 | + * JSON 4 Processing |
| 3 | + * Basic example 7: Creating a JSON Array of JSON Objects and saving it to a file. |
| 4 | + * |
| 5 | + * Good for saving multiple complex values, such as database tables. |
| 6 | + * |
| 7 | + * Author: Andreas Göransson, output additions: Tim Pulver |
| 8 | + */ |
| 9 | + |
| 10 | +import org.json.*; |
| 11 | +import java.io.File; |
| 12 | + |
| 13 | +void setup(){ |
| 14 | + |
| 15 | + // Object creation like in example 3 |
| 16 | + // ================================================= |
| 17 | + |
| 18 | + // 1. Initialize the Array |
| 19 | + JSONArray myJsonUsers = new JSONArray(); |
| 20 | + |
| 21 | + // 2. Create the first object & add to array |
| 22 | + JSONObject firstUser = new JSONObject(); |
| 23 | + firstUser.put( "name", "Andreas" ); |
| 24 | + firstUser.put( "age", 32 ); |
| 25 | + myJsonUsers.put( firstUser ); |
| 26 | + |
| 27 | + // 3. Create the second object |
| 28 | + JSONObject secondUser = new JSONObject(); |
| 29 | + secondUser.put( "name", "Maria" ); |
| 30 | + secondUser.put( "age", 28 ); |
| 31 | + myJsonUsers.put( secondUser ); |
| 32 | + |
| 33 | + // Writing the JSON Array / Object to a file |
| 34 | + // ================================================= |
| 35 | + |
| 36 | + // will store the JSON Array in the file json_output.txt within the data directory |
| 37 | + File file = new File(dataPath("") + File.separator + "json_output.txt"); |
| 38 | + // Create the data directory if it does not exist |
| 39 | + file.getParentFile().mkdirs(); |
| 40 | + try{ |
| 41 | + // If the file already exists, it will be overwritten |
| 42 | + FileWriter fstream = new FileWriter(file, false); |
| 43 | + // Use this instead if you want to append the data to the file |
| 44 | + //FileWriter fstream = new FileWriter(file, true); |
| 45 | + BufferedWriter out = new BufferedWriter(fstream); |
| 46 | + // do the actual writing |
| 47 | + myJsonUsers.write(out); |
| 48 | + // Close the stream |
| 49 | + out.close(); |
| 50 | + }catch (Exception e){ |
| 51 | + System.err.println("Error writing the JSON file: " + e.getMessage()); |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +void draw(){ |
| 56 | +} |
0 commit comments