January 21, 2011

Android and JSON

Posted in Android Development, misc tagged , , , , , , , , , at 7:12 pm by tetontech

As I have been working with Android I found that the JSON library included in the standard Android library set was the one from JSON.org which is intended as a reference implementation.  When using that implementation I found that it is much more confusing than it needs to be.  To solve this problem I created a generic Java implementation usable in any Java situation including Android.  You can get it from sourceForge.  A JavaDoc API is included in the download.

Like the JavaScript implementation from JSON.org that is being embedded in all new browsers my implementation has stringify and parse methods.  These methods behave just like the ones in JavaScript and are static methods of the JSONUtilities class.

The stringify method  receives most any Serializable object, runs up its inheritance tree, and returns a JSON string that includes all of the attributes of all of the objects and all of the values from all of the collections found.  The only Serializable objects not accepted are raw Java Objects, since they have no attributes, and anything that inherits from java.awt.container.

The JSONUtilities.parse method takes a JSON formatted string as its parameter and returns either a HashMap or an ArrayList.  What is returned is dependent upon if the JSON container is an array or an associative array(object/map).

Here is an example from the JavaDocs of the string being parsed and what is produced.

  • Example 1 JSON: [“1”, “hello”, {“name”:”fred”,”age”:”23″}]
  • Example 1 Result: An ArrayList with three values: a String “1”, a String “hello”, and a HashMap as the third value in the ArrayList. This HashMap has two key/value pairs: “name”/”fred” and “age”/”23”.

 

  • Example 2 JSON: {“state”:”Idaho”, “city”:”Rexburg”, “people”:[“bob”,”sue”]}
  • Example 2 Result: A HashMap with three key/value pairs: “state”/”Idaho”, “city”/”Rexburg”, and “people”/ArrayList. The ArrayList that is the value for the “people” key has two String values “bob” and “sue”.

Object anObject = JSONUtilities.parse(aJSONString);

Here is an example of how the JSONUtilities stringify method works.

  • Example 1 Object: An ArrayList with three values: a String “1”, a String “hello”, and a HashMap as the third value in the ArrayList. This HashMap has two key/value pairs: “name”/”fred” and “age”/”23”.
  • Example 1 JSON result: [“1”, “hello”, {“name”:”fred”,”age”:”23″}]

 

  • Example 2 Object: A HashMap with three key/value pairs: “state”/”Idaho”, “city”/”Rexburg”, and “people”/ArrayList. The ArrayList that is the value for the “people” key has two String values “bob” and “sue”.
  • Example 2 JSON result: {“state”:”Idaho”, “city”:”Rexburg”, “people”:[“bob”,”sue”]}

String  jsonString = JSONUtilities.stringify(anObject);

 

In addition to these two utility methods there are two stream wrapper classes.  These behave much the ObjectOutput stream methods that are part of JavaSE.  They allow you to JSON an object into a stream and parse an object out of a stream.  These streams can be anything that inherits from InputStream or OutputStream.  For example, these could be a FileInputStream, a FileOutputStream, an input or output stream from a socket, etc.

Here is a code sample where the JSONOutputStream is wrapped around a FileOutputStream.  This would write the JSON to a file on disk.

HashMap aMap = new HashMap();

aMap.put(“stringOne”, “Some sort of string”);

aMap.put(“aNumber”, 16.5);

aMap.put(20,”some other stuff” );

aMap.put(“aTesterDate”,new Date());

try{

FileOutputStream aFileOutStream = new FileOutputStream(“testFile.txt”);

JSONOutputStream aJSONFileStream = new JSONOutputStream(aFileOutStream);

aJSONFileStream.writeObject(aMap);

}

catch(Exception e){

//do your exception handling

}

 

The code to read and parse JSON from a stream is similar.  Here is an example reading from a file.

try {

FileInputStream aFileInputStream = new FileInputStream(“testFile.txt”);

JSONInputStream inFromFile = new JSONInputStream(aFileInputStream);

Object anObject = inFromFile.readObject();

//if anObject is expected to be an ArrayList cast it as such and use it.

//if anObject is expected to be a HashMap cast it as such and use it.

} catch (Exception e) {

//do your exception handling here

}

 

I hope this helps you with your data communications in Android, JavaSE, and Java Enterprise.

 

Advertisements

2 Comments »

  1. ahmed said,

    Can you show us how to display images

    • tetontech said,

      In what way? Are you intending to pull the image dat using JSON? That is usually a bad idea.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: