About myJSON

What is myJSON?

myJSON is a small (25Kb) and "to-the-point" Java library for handling object literals in JSON or JavaScript notation. It goes beyond the usual Java -> JSON -> notation in that provides classes for updating Java objects with JSON data and for comparing a Java object with a JSON object.

One particular place where I find this extremely useful is for writing quick and precise unit tests that have to set or verify the contents of an object graph.

If you don't know what JSON notation is, well it's a lighweight syntax for representing objects as plaint text, much lighter (albeit less flexible) than XML. Objects are represented as name-value pairs delimited by { } braces. For example:

{ x:3, y:4, location:'Madrid'}

repersents an object with two numeric fields, called x and y, and a string field called location.  Since JSON notation comes from the syntax of literal objects in JavaScript, no type information is present.

In JSON notation, arrays (or lists) are represented as a list of comma-separated values delimited by square brackets []:

{ name:'Peter', friends:['Alice','Bob','Elsa'], puppets:['Fido','Garfield']}

A quick example

Imagine you have these two Java classes:

public class Address {
  public String street;
  public String zip;

}


public class User {
  public Address addr;
  public String name;
  public int age;
  public ArrayList<String> friends;
}  
 

Now, you can use the Updater class to assign a value to selected fields of the object:

User u = new User();
Updater.update(u,"{name:'Peter',addr:{street:'Grand Ave,32'},friends:['Alice','Bob']}");

Note that in the previous example:

You can then use the Comparator class to compare a Java object with a specified JSON object:

if (Comparator.compare(u,"{name:'Peter',friends:['Alice','Bob']}")) 
 	...
}

And of course, you have the Parser class which will parse an object literal and return a Java representation of its data:

Object data = Parser.parse("{x:3, y:3, z:3, color:{r:250,g:80,b:95}}");

and the Serializer class which will perform the reverse operation - representing a Java object as an object literal in JSON notation:

User user = new User();
....
String s = Serializer.serializeObject(user)

You can tell the serializer to serialize only a specified set of fields, based on their names:

User user = new User();
....
String s = Serializer.serializeObject(user,"name","friends")

This quick example uses the "quick and dirty" methods that use the default settings of the different classes. You can, for example, configure whether the serializer will explore all fields or only fields with getter/setter accessors, whether transient fields are included, and more.

For a more detailed documentation please see the included Javadoc.