/home/wpollock1/public_html/AJava/JSONdemo.java
// This is a demo of org.json, available from:
// https://repo1.maven.org/maven2/org/json/json/20160810/
// Download the current jar file and make sure it can be found on
// CLASSPATH. API docs are also available there for download ("javadoc.jar").
// This package is simple to use and good for an introductory demo, but isn't
// as powerful as some newer Java JSON libraries.
//
// Written 3/2012 by Wayne Pollock, Tampa Florida USA
import org.json.*;
import java.io.*;
import java.util.*;
public class JSONdemo {
public static void main ( String [] args ) throws Exception {
// Create a JSON object from scratch:
JSONObject jo1 = new JSONObject()
.put( "string", "JSON demo" )
.put( "integer", 1 )
.put( "double", 2.5 )
.put( "boolean", true );
// Create a JSON object from a Java Map:
Map<String,Object> map = new HashMap<>();
map.put( "name", "Hymie" );
map.put( "age", 42 ); // Uses auto-boxing
map.put( "address", new String[]{
"123 Main Street", "Anytown, USA", "12345" } );
JSONObject jo2 = new JSONObject( map );
// Save the two objects to a file:
PrintStream out = new PrintStream( new FileOutputStream( "json.txt" ) );
out.println( jo1 );
out.println( jo2 );
out.close();
// Read JSON from a file, and create a Java Map:
BufferedReader in = new BufferedReader( new FileReader("json.txt") );
String jsonText1 = in.readLine();
String jsonText2 = in.readLine();
in.close();
JSONObject jo3 = new JSONObject( jsonText1 );
JSONObject jo4 = new JSONObject( jsonText2 );
System.out.println( jo3 + "\n" );
Map<String,Object> map2 = new HashMap<>();
Iterator it = jo4.keys();
while ( it.hasNext() ) {
String name = (String) it.next();
Object value = jo4.get( name );
System.out.println( "Name: " + name + ", value: " + value );
map2.put( name, value );
}
System.out.println( "\nReconstructed map: " + map2 );
}
}