org.less4j
Class JSON

java.lang.Object
  extended by org.less4j.JSON
Direct Known Subclasses:
JSONR

public class JSON
extends java.lang.Object

A relatively strict JSON intepreter to evaluate a UNICODE string as a tree of basic Java instances with maximum limits on the number of containers and iterations, plus static methods to serialize java objects as JSON strings.

Synopsis

Conveniences JSON static methods allow to evaluate strings as an untyped Object, a JSON.Object map or a JSON.Array list:

JSON json = new JSON() 
try {
    Object value = json.eval("null");
    JSON.Object map = json.object("{\"pass\": true}");
    JSON.Array list = json.array("[1,2,3]");
} catch (JSON.Error e) {
    System.out.println(e.getMessage())
}

Access them simply and practically:

try {
    if (map.bool("pass"))
        BigInteger i = list.intg(2);
} catch (JSON.Error e) {
    System.out.println(e.getMessage())
}

Serialize java instances as JSON strings:

System.out.println(JSON.encode(value));
System.out.println(JSON.encode(map));
System.out.println(JSON.encode(list));

Note that you can serialize not just the types instanciated by JSON but also any Map or List of many other java object.

Also, JSON object are serialized with their properties sorted by names, allowing to compare two objects for equality by comparing such string. That's handy in many case, most remarkably in order to sign and check digest for JSON objects.

Interpreter

Direct instanciation of an Interpreter is usefull to evaluate many strings under the same global constraints on their cumulated numbers of containers and iterations.

It's practical to evaluate distinct JSON values:

JSON json = new JSON();
try {
    Object one = json.eval("{\"size\": 0}");
    Object two = json.eval("[1.0, true, null]");
    Object three = json.eval("1.0");
    Object four = json.eval("true");
    Object five = json.eval("null");
} catch (JSON.Error e) {
    System.out.println(e.getMessage());
}

To update any instance of Map with the members of many JSON objects:

JSON.Error e;
JSON json = new JSON();
HashMap map = new HashMap(); 
e = json.update(map, "{\"width\": 200}");
if (e != null)
    System.out.println(e.str());
e = json.update(map, "{\"pass\": 1, fail: true}");
if (e != null)
    System.out.println(e.str());

To extend any List with the collection of many JSON arrays:

JSON json = new JSON();
ArrayList list = new ArrayList(); 
e = json.extend(list, "[1,2,3]");
if (e != null)
    System.out.println(e.str());
e = json.extend(list, "[null, true, 1.0]");
if (e != null)
    System.out.println(e.str());

JSON Types

A convenience with static methods to serialize java objects as JSON strings and to evaluate a strict JSON expression as a limited tree of the five Java types

String, Double, BigDecimal, BigInteger, Boolean,
two convenience extending HashMap and ArrayList, plus the untyped null value.

.

Note that the additional distinction between JSON number types is made by considering numbers with an exponent as Doubles, the ones with decimals as BigDecimal and the others as BigInteger.

Safety Limits

Lower limits than the defaults maximum of 65355 can be set for the number of objects and arrays and the count of values, for containers and iterations:

try {
    JSON.Array list = (new JSON(1, 4)).array("[1,2,3,4,5]");
} catch (JSON.Error e) {
    System.out.println(e.getMessage())
}
making JSON evaluation safe for public interfaces.

Serialization

To append distinct values into a StringBuffer

StringBuffer sb = new StringBuffer();
sb.append("{\"size\":");
JSON.strb(sb, value);
sb.append(",\"map\": ");
JSON.strb(sb, map);
sb.append(",\"list\": ");
JSON.strb(sb, list.iterator());
sb.append("}");
System.out.println(sb.toString());
using templates for constants.

Pretty Print

To pretty print an indented representation of a java instance in JSON:

System.out.println(JSON.repr(value));
System.out.println(JSON.repr(map));
System.out.println(JSON.repr(list));
...

Copyright © 2006 Laurent A.V. Szyster

Version:
0.30

Nested Class Summary
static class JSON.Array
          An extension of ArrayList with type-casting convenience methods that throw JSON.Error or return a typed object.
static class JSON.Error
          A simple JSON exception throwed for any syntax error found by the interpreter.
static class JSON.Object
          An extension of HashMap with type-casting convenience methods that throw JSON.Error or return a typed object.
 
Field Summary
 int containers
          The maximum number of containers left to instanciate by this parser.
 int iterations
          The maximum number of iterations left to for this parser.
 
Constructor Summary
JSON()
          Instanciate a JSON interpreter with limits set to 65355 on the number of containers and iterations.
JSON(int containers, int iterations)
          Instanciate a JSON interpreter with the given limits on the number of both containers and iterations.
 
Method Summary
 JSON.Array array(java.lang.String json)
          Evaluates a JSON array, returns a new JSON.Array or throws a JSON.Error if the string does not represent a valid array or if it exceeds the limits on containers and iterations.
static java.lang.String encode(java.lang.Object value)
          Encode an untyped value as a JSON string, return a String that can safely be encoded in UTF-8.
 java.lang.Object eval(java.lang.String json)
          Evaluates a JSON String as an untyped value, returns a JSON.Object, JSON.Array, String, BigDecimal, BigInteger, Double, Boolean, null or throws a JSON.Error if a syntax error occured.
 JSON.Error extend(java.util.List list, java.lang.String json)
          Evaluates a JSON String and extends a List, return null or a JSON.Error if the string does not represent a valid array.
 JSON.Object object(java.lang.String json)
          Evaluates a JSON object, returns a new JSON.O or throws a JSON.Error if the string does not represent a valid object or if it exceeds the limits set on the number of containers and iterations.
static java.lang.String repr(java.lang.Object value)
          Encode an untyped value as a pretty-printed JSON string with CRLF line delimiters and a two space wide indentation, return a String that can safely be encoded in UTF-8.
static java.lang.StringBuffer strb(java.lang.StringBuffer sb, java.util.Iterator it)
           
static java.lang.StringBuffer strb(java.lang.StringBuffer sb, java.util.Map map, java.util.Iterator it)
           
static java.lang.StringBuffer strb(java.lang.StringBuffer sb, java.util.Map map, java.lang.Object[] names)
           
static java.lang.StringBuffer strb(java.lang.StringBuffer sb, java.lang.Object value)
           
static java.lang.StringBuffer strb(java.lang.StringBuffer sb, java.lang.String s)
           
 JSON.Error update(java.util.Map map, java.lang.String json)
          Evaluates a JSON String and update a Map, return null or a JSON.Error if the string does not represent a valid object.
static java.lang.String xjson(java.lang.Object value)
          Encode an untyped value as a JSON string, return a String that can safely be encoded in 7bit ASCII.
 
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

containers

public int containers
The maximum number of containers left to instanciate by this parser.


iterations

public int iterations
The maximum number of iterations left to for this parser.

Constructor Detail

JSON

public JSON()
Instanciate a JSON interpreter with limits set to 65355 on the number of containers and iterations.


JSON

public JSON(int containers,
            int iterations)
Instanciate a JSON interpreter with the given limits on the number of both containers and iterations.

Parameters:
containers - a limit on the number of objects and arrays
iterations - a limit on the total count of values
Method Detail

array

public JSON.Array array(java.lang.String json)
                 throws JSON.Error
Evaluates a JSON array, returns a new JSON.Array or throws a JSON.Error if the string does not represent a valid array or if it exceeds the limits on containers and iterations.

Parameters:
json - String to evaluate
Returns:
a new JSON.Array array
Throws:
JSON.Error

encode

public static final java.lang.String encode(java.lang.Object value)
Encode an untyped value as a JSON string, return a String that can safely be encoded in UTF-8.

Parameters:
value - to encode
Returns:
a JSON String

eval

public java.lang.Object eval(java.lang.String json)
                      throws JSON.Error
Evaluates a JSON String as an untyped value, returns a JSON.Object, JSON.Array, String, BigDecimal, BigInteger, Double, Boolean, null or throws a JSON.Error if a syntax error occured.

Parameters:
json - string to evaluate
Returns:
an untyped Object
Throws:
JSON.Error

extend

public JSON.Error extend(java.util.List list,
                         java.lang.String json)
Evaluates a JSON String and extends a List, return null or a JSON.Error if the string does not represent a valid array.

Parameters:
list - the List to extend
json - String to evaluate
Returns:
null or a JSON.Error

object

public JSON.Object object(java.lang.String json)
                   throws JSON.Error
Evaluates a JSON object, returns a new JSON.O or throws a JSON.Error if the string does not represent a valid object or if it exceeds the limits set on the number of containers and iterations.

Parameters:
json - string to evaluate
Returns:
a new JSON.O
Throws:
JSON.Error

repr

public static final java.lang.String repr(java.lang.Object value)
Encode an untyped value as a pretty-printed JSON string with CRLF line delimiters and a two space wide indentation, return a String that can safely be encoded in UTF-8.

Parameters:
value - to represent
Returns:
an X-JSON String

strb

public static final java.lang.StringBuffer strb(java.lang.StringBuffer sb,
                                                java.util.Iterator it)

strb

public static final java.lang.StringBuffer strb(java.lang.StringBuffer sb,
                                                java.util.Map map,
                                                java.util.Iterator it)

strb

public static final java.lang.StringBuffer strb(java.lang.StringBuffer sb,
                                                java.util.Map map,
                                                java.lang.Object[] names)

strb

public static final java.lang.StringBuffer strb(java.lang.StringBuffer sb,
                                                java.lang.Object value)

strb

public static final java.lang.StringBuffer strb(java.lang.StringBuffer sb,
                                                java.lang.String s)

update

public JSON.Error update(java.util.Map map,
                         java.lang.String json)
Evaluates a JSON String and update a Map, return null or a JSON.Error if the string does not represent a valid object.

Parameters:
map - the Map to update
json - String to evaluate
Returns:
null or a JSON.Error

xjson

public static final java.lang.String xjson(java.lang.Object value)
Encode an untyped value as a JSON string, return a String that can safely be encoded in 7bit ASCII.

Parameters:
value - to encode
Returns:
an X-JSON String