Java Reference
In-Depth Information
Parsing and Writing JSON with org.json
Problem
You want to read/write JSON using a mid-sized, widely used JSON API.
Solution
Consider using the org.json API; it's widely used and is also used in Android.
Discussion
The org.json package is not as advanced as Jackson, nor as high-level; it makes you think
and work in terms of the underlying JSON abstractions instead of at the Java code level. For
example, here is the org.json version of reading the software description from the opening of
this chapter:
public
public class
class SoftwareParseOrgJson
SoftwareParseOrgJson {
final
final static
static String FILE_NAME = "/json/softwareinfo.json" ;
public
public static
static void
void main ( String [] args ) throws
throws Exception {
InputStream jsonInput =
SoftwareParseOrgJson . class . getResourceAsStream ( FILE_NAME );
iif ( jsonInput == null
null ) {
throw
throw new
new NullPointerException ( "can't find" + FILE_NAME );
}
JSONObject obj = new
new JSONTokener ( jsonInput ));
System . out . println ( "Software Name: " + obj . getString ( "name" ));
System . out . println ( "Version: " + obj . getString ( "version" ));
System . out . println ( "Description: " + obj . getString ( "description" ));
System . out . println ( "Class: " + obj . getString ( "className" ));
JSONArray contribs = obj . getJSONArray ( "contributors" );
for
new JSONObject ( new
for ( int
int i = 0 ; i < contribs . length (); i ++) {
System . out . println ( "Contributor Name: " + contribs . get ( i ));
}
}
}
 
 
 
 
Search WWH ::




Custom Search