JSONdemo.java

Download JSONdemo.java

 1: // This is a demo of org.json, available from:
 2: //    https://repo1.maven.org/maven2/org/json/json/20160810/
 3: // Download the current jar file and make sure it can be found on
 4: // CLASSPATH.  API docs are also available there for download ("javadoc.jar").
 5: // This package is simple to use and good for an introductory demo, but isn't
 6: // as powerful as some newer Java JSON libraries.
 7: //
 8: // Written 3/2012 by Wayne Pollock, Tampa Florida USA
 9: 
10: import org.json.*;
11: import java.io.*;
12: import java.util.*;
13: 
14: public class JSONdemo {
15:   public static void main ( String [] args ) throws Exception {
16:     // Create a JSON object from scratch:
17:     JSONObject jo1 = new JSONObject()
18:         .put( "string", "JSON demo" )
19:         .put( "integer", 1 )
20:         .put( "double", 2.5 )
21:         .put( "boolean", true );
22: 
23:     // Create a JSON object from a Java Map:
24:     Map<String,Object> map = new HashMap<>();
25:     map.put( "name", "Hymie" );
26:     map.put( "age", 42 );  // Uses auto-boxing
27:     map.put( "address", new String[]{
28:        "123 Main Street", "Anytown, USA", "12345" } );
29: 
30:     JSONObject jo2 = new JSONObject( map );
31: 
32:     // Save the two objects to a file:
33:     PrintStream out = new PrintStream( new FileOutputStream( "json.txt" ) );
34:     out.println( jo1 );
35:     out.println( jo2 );
36:     out.close();
37: 
38:     // Read JSON from a file, and create a Java Map:
39:     BufferedReader in = new BufferedReader( new FileReader("json.txt") );
40:     String jsonText1 = in.readLine();
41:     String jsonText2 = in.readLine();
42:     in.close();
43: 
44:     JSONObject jo3 = new JSONObject( jsonText1 );
45:     JSONObject jo4 = new JSONObject( jsonText2 );
46:     System.out.println( jo3 + "\n" );
47: 
48:     Map<String,Object> map2 = new HashMap<>();
49:     Iterator it = jo4.keys();
50:     while ( it.hasNext() ) {
51:       String name = (String) it.next();
52:       Object value = jo4.get( name );
53:       System.out.println( "Name: " + name + ", value: " + value );
54:       map2.put( name, value );
55:     }
56:     System.out.println( "\nReconstructed map: " + map2 );
57:   }
58: }